Useful article taking the mystery out of how Javascript functions work

I found this useful. It helps to understand what’s really happening rather than following recipes, because then you can understand what you need to do.

JavaScript, 5 ways to call a function.

The information about assigning event handlers is very useful.

This article is part of a series which I’ll have to look at.

This lead me to one of the staples of Object Orientated play – shapes. A simple circle class using some encapsulation techniques I’d seen elsewhere was:

var Circle = function(){
	// An example of a private method, contained within Closure Scope.
	// All private state would seem to be singleton (or making non-singleton private
	// state seems hard and pointless).
	var square = function(r){
		return r*r;
	};

	// The Constructor that I am creating. The name of this method becomes the
	// class name in the debugger.
	var Circle = function(x,y,r){
		this.x = x;
		this.y = y;
		this.r = r;
	};

	// Create a Prototype.
	Circle.prototype = 
	{
			toString : function(){
				return "Circle[" + this.x + "," + this.y + "," + this.r + "]";
			},

			getArea : function(){
				return square(this.r);
			}
	};

	return Circle;
}();

This becomes interesting when we try to abstract out the concept of Shape, so “Circle is a Shape”. It may be tempting to place information on Shape such as the position, but Javascript uses prototypes which work very differently to inheritance in a language like Java.

This entry was posted in javascript. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.