I am reading about closures in “Javascript: The Good Parts” book.
There is following example of using closures:
var add_the_handlers = function (nodes) {
var i;
for (i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = function (i) {
return function (e) {
alert(i + ":" + e);
};
}(i);
}
};
Is it correct example? Or much correct example would be following?
var add_the_handlers = function (nodes) {
var i;
for (i = 0; i < nodes.length; i += 1) {
nodes[i].onclick = function (idx) {
return function (e) {
alert(idx + ":" + e);
};
}(i);
}
};
Variable i in the outer function and variable i in the inner function “nodes[i].onclick = function (i)” – it is two different variables.
And third function accesses variable from second function, not from the outermost.
Am I correct?
The two examples are identical. The whole point of a closure is to make an outer-scoped variable (i) into an inner-scoped variable (i/idx/foo, take your pick). The closure creates a “copy” of the variable, so that when the callback gets made, it has the correct value.