A Most Useful Tutorial on Javascript Closures

It can be very difficult to understand what Javascript closures are and why they are useful.  The very most useful explanation I have ever found is this bit of code below, which shows how closures can make private variables in Javascript and how to create getters and setters to retrieve and manipulate the private variable.

var person = function () {
	// Private
	var name = "Robert";
	return {
		getName : function () {
			return name;
		},
		setName : function (newName) {
			name = newName;
		}
	};
}();
alert(person.name); // Undefined
alert(person.getName()); // "Robert"
person.setName("Robert Nyman");
alert(person.getName()); // "Robert Nyman"

In this code, a self-executing function creates an object with two methods, getName and setName.  Both methods are closures which have access to the private name variable that was created in the self-executing function.  The object, stored here in the person variable, does not itself have access to the private name variable.  However, the getters and setters both have access to the same name variable since they were both created in the same local scope in which the closure was created.  I may not be totally describing this right but if you look at the code you’ll probably figure out why it’s useful.  This is the best explanation I’ve seen because it’s immediately apparent how practical this is, especially how you can limit access to and manipulation of the private variable only via the getter and setter methods.

This explanatory code is from the blog post Explaining JavaScript scope and closures

Here’s another example, from http://stackoverflow.com/questions/3564238/object-oriented-javascript-with-prototypes-vs-closures

With closure-based implementation you can have private variables and 
methods (just don't expose them in the this object). 
So you can do something such as: 

function Book(title) { 
var title_; 
this.getTitle = function() { return title_; }; 
this.setTitle = function(title) { title_ = title; };
 // should use the setter in case it does something else than 
just assign this.setTitle(title); } 

Code outside of the Book function can not access the member 
variable directly, they have to use the accessors. 
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: