Simple example of closure:
function sayHello(name) {
var text = 'Hello ' + name; // local variable
var sayAlert = function() { console.log(text); }
return sayAlert;
}
var say = sayHello( "fefefe");
say();
sayAlert holds a reference to text. text as a local variable is accessible outside of the scope
In C, and most other common languages after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed.
In JavaScript, if you declare a function within another function, then all the local variables including parameters can remain accessible after returning from the function you called.
Local variables are not copied but referenced by closure
function say667(){
var num = 666;
var sayAlrt = function(){alert(num);}
num++;
return sayAlert;
}
var sayNumba = say667();
sayNumba();//667
Useful example:
// Define a function that sets a DOM node's color
// to yellow and then fades it to white.
var fade = function (node) {
var level = 1;
var step = function ( ) {
var hex = level.toString(16);
node.style.backgroundColor = '#FFFF' + hex + hex;
if (level < 15) {
level += 1;
setTimeout(step, 100);
}
};
setTimeout(step, 100);
};
fade(document.body);
Avoid creating functions in the LOOP, because function returned will always be the same!
Tutorial and reference: http://www.javascriptkit.com/javatutors/closures.shtml