Ad

Simple Javascript Closure Issue

- 1 answer

I know WHY this doesn't work, but can't find the correct way of doing it.

I'm trying to build an object using a loop. The Object builds fine, but when I try to use the callback, it alerts "2" for each person, I'd like it to alert the position in the array.

var playerArr = ["steve", "paul", "bob"];

var myAutomatedObj = {};
for (var i=0; i<playerArr.length; i++){
    var objName = playerArr[i];
    myAutomatedObj[objName] = {};
    myAutomatedObj[objName]["callback"] = function(){
        alert(i);
    }
}

//returns incorrect alert
myAutomatedObj.steve.callback();
Ad

Answer

The property i is referenced by each function, because it's in their scope, but its value equals the length of the array at the end of the loop.

Try the following:

myAutomatedObj[objName]["callback"] = (function(j) {
    return function(){
        alert(j);
    }
})(i);

This way you actually copy the value and you are no longer referencing the variable named i.

Ad
source: stackoverflow.com
Ad