A closure is a construct in which you reference a variable outside the scope in which it's defined. You usually talk about closures in the context of a function.
var helloFunction;
var finished = false;
while (!finished) {
var message = 'Hello, World!';
helloFunction = function() {
alert(message);
}
finished = true;
}
helloFunction();
Here, I define the variable message, and define a function that references message. When I define the function to use message, I am creating a closure. This means helloFunction holds a reference to message, so that I can continue to use message, even outside of the scope (the loop body) where message is defined.
Addendum
The (i) in parenthesis is a function call. What's happening is:
- You define some function(num) {}. This is called an anonymous function, because it's defined inline and doesn't have a name.
- function(num) takes an integer argument, and returns a reference to another function, which is defined as alert(num)
- The outer anonymous function is immediately called, with the argument i. So num=i. The result of this call is a function which will do alert(i).
- The end result is more or less equivalent to:
link.onclick = function() { alert(i); };