-2

Possible Duplicate:
How do JavaScript closures work?

I understand that one issues people have with closures is that it returns the lastest value for a given variable unless you do this:

function f() {
    var a = [];
    var i;

    for (i = 0; i < 3; i++) {
        a[i] = (function (x) {
            return function () {
                return x;
            }
        })(i);
    }
    return a;
}
}

There is a little too much going on there that I need explained.

Community
  • 1
  • 1
Blankman
  • 259,732
  • 324
  • 769
  • 1,199
  • 2
    Please be specific on your questions. You should have known that by now. – hugomg Jul 30 '11 at 14:33
  • 2
    It seems like you added a `}` too many. – pimvdb Jul 30 '11 at 14:33
  • check out this question for a good explanation of how closures work in javascript http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Charles Ma Jul 30 '11 at 14:37
  • @Blankman: You may find it easier to comprehend if you replace the IIFE `(function (x) { return func... })(i);` with a *named* function that is called in the loop: `for(i=0...){some_func(i);}`. Then `some_func` would receive `i`, defined as parameter `x`, and return a function that references `x`. `function some_func( x ) { return function(){ return x; }; }` – user113716 Jul 30 '11 at 16:19

1 Answers1

1

In JavaScript, the scope of a variable is always a function (or the global object). So, if you do something like

for (var i = 0; i < 3; i++) {
    a[i] = function (x) {
        return i;
    };
}

there is only ONE i involved. After the for loop finishes, the value of i is 2, no matter which of the a[i] functions is called.

To work around this, we need to establish a new scope. Usually this is done by invoking an anonymous function like so:

a[i] = (function (x) { // (1)
    return function () { //  (2)
        return x;
    };
})(i);

Now the i at iteration time is mapped to a brand new x for each iteration, and the function (1) makes sure it gets "trapped" until a[i] (2) is executed.

user123444555621
  • 148,182
  • 27
  • 114
  • 126