In the following snippet, why and how does the calling the function form a brand new execution context where the value of i is retained?
function getHandler(n) {
return function() {
alert( 'You clicked on: ' + n );
};
}
for (var i = 0; i < 100; ++i) {
myElements[i].onclick = getHandler(i);
}
It’s caused by JavaScript closures and the behavior of variables declared in a for loop in JavaScript. Because the argument
nis part ofaddHandler‘s closure, n maintains it’s value for the function instances declared inside of itself. It just so happens that your passing in i from a for loop in the global space.Here is a fiddle showing that behavior.
If you were to do something to increment
ninside ofaddHandler, you would see that it doesn’t actually effecti. Once again, this is because of closure,nexists inside ofaddHandler‘s closure and was merely populated byi.Here is a fiddle showing that behavior.
Because of closure,
nwill exist for however long whatever is created inside ofaddHandler(in this case some function references) exist.I hope that makes sense. It’s tricky to explain, I think.
EDIT: Here is an awesome explanation of JavaScript closures and how they work.