Unusual behavior of variables captured by a clusure in a for [duplicate]

2

Consider an object obj any:

obj = {q: 1, w: 2, e: 3, r: 4, t: 5, y: 6};

Now I'm iterating under the object's keys and creating an anonymous function that uses this key:

list = []
for (var key in obj) {
    list.push(function() {
        return key;
    });
}

But this does not work: console.log(list[0]()) // isso mostra "y" . It is as if the variable key used was always that of the last iteration and not that of the iteration that created the function. Modifying this does not solve the problem:

list = []
for (var key in obj) {
    var dummy = key;
    list.push(function() {
        return dummy;
    });
}

Even though I have created a different variable in each iteration and referred to its value specifically, the result is the same. Not even writing something like the following works.

list = []
var keys = Object.keys(obj);
for (var i = 0; i < keys.length; ++i) {
    var key = keys[i];
    list.push(function() {
        return key;
    });
}

Why? What's going on here? How to write a code that does the proposed?

    
asked by anonymous 16.05.2014 / 20:40

1 answer

2
  

Duplicate of < How to use the current value of a variable in a more internal function?

Solution: Use a function immediately invoked to give a scope for the variable.

list = []
for (var key in obj) {
    (function(key) {
        list.push(function() {
            return key;
        });
    })(key);
}
    
16.05.2014 / 21:06