Reputation: 1049
Option 1:
function addLinks () {
for (var i=0, link; i<5; i++) {
link = document.createElement("a");
link.innerHTML = "Link " + i;
link.onclick = function () {
alert(i);
};
document.body.appendChild(link);
}
}
window.onload = addLinks;
Option 2:
function addLinks () {
for (var i=0, link; i<5; i++) {
link = document.createElement("a");
link.innerHTML = "Link " + i;
link.onclick = function (num) {
return function () {
alert(num);
};
}(i);
document.body.appendChild(link);
}
}
window.onload = addLinks;
I know Option 1: will output 5 everytime you click because of closure, but Option 2 will output the right result, 0,1,2...
My question is: How does Option 2 resolve the problem? how does Option 2 work?
Upvotes: 0
Views: 89
Reputation: 44376
The variable in Option 1, i
, is at the scope of the function addLinks()
(because it is declared as a var in that function). It's only called once, there's only one scope shared by all five of functions assigned to onclick.
In Option 2, the variable num
is in the scope of the anonymous function (because it is a formal parameter to that function). It's called five times; there are five separate scopes, one for each of the five functions assigned to onclick.
Does that help?
Upvotes: 4