0

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?

user2294256
  • 1,029
  • 1
  • 13
  • 22
  • 1
    You might want to take a look at this [SO question](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work). It has lots of useful replies to help you understand how closures work. – excentris Jul 03 '13 at 06:06
  • 1
    This may help you http://stackoverflow.com/questions/111102/how-do-javascript-closures-work?rq=1 – 웃웃웃웃웃 Jul 03 '13 at 06:07

1 Answers1

4

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?

Michael Lorton
  • 43,060
  • 26
  • 103
  • 144
  • +1 was going to write the same. In fact in #1, 5 closures are created, all referring to the same variable. In #2, 10 closures are created where as 5 refer to i but are immediately evaluated (immediate function). The 5 inner closures refer to 5 newly created variables with 5 different values. – chiccodoro Jul 03 '13 at 06:32