Consider this example:
for(var j = 0; j < 10; j++)
{
setTimeout(function()
{
alert(j);
}, 1000);
}
A closure wraps the reference to the variable so it can access it when the function is invoke. In the above example, every call captures the same reference to j; ergo all functions capture the same reference and all will alert '10'. Now consider this example:
for(var j = 0; j < 10; j++)
{
var innerReference = j;
setTimeout(function()
{
alert(innerReference);
}, 1000);
}
In this example, each iteration of the loop captures the reference to the newly created 'innerReference' variable; and each iteration creates a new innerReference
. Ergo, this time they display 1, 2, 3, 4, etc and so forth.
At a basic level, it's pretty much like this; a closure is the capture of a reference to another variable outside to what would normally be the scope of that object.