a ninja in waiting ...

Mark Caudill

There isn’t a huge conspiracy to hide what closures mean to the power of JavaScript, but the principles can be easily understood.

A closure is actually more liberating than the name implies.  It opens the door to new possibilities by passing variables between lower-level functions.

Take for example, a very simple closure:

var ourFunction = function() {
var ourFunction2 = function() { alert(ourVar); };
var ourVar = "A simple JavaScript closure.";

ourFunction2();
};

As you can see, the ourVar variable is available to ourFunction2 despite ourVar being defined in the scope of ourFunction (locally).  Even if ourFunction2 wasn’t defined inside of ourFunction, we’d still have access to ourVar.  Similarly, if ourVar was a parameter of ourFunction, we’d still have access to it within ourFunction2.
(more…)

WordPress theme by Mark Caudill.