Javascript Closures

Closures are one of the most fascinating constructs ever IMHO.
Not many people know about their existence, let alone in Javascript.
However the knowledge of them can seriously leverage your designs.

So what is a closure? A function that keeps an environment.
The best way to explain a closure is with an example, so
thats what I will show you.


var globalVariable = 20;

function createClosure(arg)
{
var env = 10;
return function(x) { alert ( arg + env + x ); }
}

// main body
ourClosure = createClosure(globalVariable) ;
globalVariable = 0;
ourClosure(30); // prints 60
alert(globalVariable); // prints 0


ourClosure() will return 60 even though we have just set the value of
the globalVariable to 0. That is, it keeps the values defined
when the closure was created.

alert(globalVariable) will output 0, the current value of globalVariable.