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. 
Advertisements

Loop–droning English postpunk/psychadelic/shoegaze (Spacemen 3, Hawkwind)

Loop is an awesome postpunk/shoegaze/psychadelic/art rock band from the 1980s, sometimes compared to earlier Spacemen 3. Kind of like mixing Suicide, Spacemen 3, Hawkwind, My Bloody Valentine, Godflesh, Swervedriver, and Sonic Youth, very droney-and repetitive but good stuff! Gilded Eternity and Fade Out seem to be their best albums…

Loop–Afterglow

Hawkwind–Born to Go