I’m reading about closures, and I had difficulty understanding the difference between these 2 code snippets:
var myElements = [ /* DOM Collection */ ];
for (var i = 0; i < 100; ++i) {
myElements[i].onclick = function() {
alert( 'You clicked on: ' + i );
};
}
The above code should only display i as 99 for every onclick
function getHandler(n) {
return function() {
alert( 'You clicked on: ' + n );
};
}
for (var i = 0; i < 100; ++i) {
myElements[i].onclick = getHandler(i);
}
And this code above displays the correct value of ‘i’ for every element click event!
I can’t understand why the 1st one doesn’t display the correct value of i. And if not, why does the 2nd one display the correct value??
They were taken from this link
It’s because the closure doesn’t capture the value of
i, but rather, the actual local variablei. When you go on to change the value ofi, the closure sees those changes, because it’s still using that same variable.Because in the second one, the closure is capturing the local variable
n, which never changes thereafter. (Later calls togetHandlerhave a completely new local variablen; this is important, not just for closures, but also for support for recursion. Otherwise different calls to a function could accidentally mess with each other’s variables!)