function celebrityIDCreator(theCelebrities) {
var i;
var uniqueID = 100;
for (i = 0; i < theCelebrities.length; i++) {
theCelebrities[i]["id"] = function () {
return uniqueID + i;
};
};
return theCelebrities;
}
var actionCelebs = [
{ name: "Stallone", id: 0 },
{ name: "Cruise", id: 0 },
{ name: "Willis", id: 0 }
];
var createIdForActionCelebs = celebrityIDCreator(actionCelebs);
var stalloneID = createIdForActionCelebs[0];
console.log(stalloneID.id()); // 103
In the preceding example, by the time the anonymous functions are called, the value of i is 3 (the length of the array and then it increments). The number 3 was added to the uniqueID to create 103 for ALL the celebritiesID. So every position in the returned array get id = 103, instead of the intended 100, 101, 102.
I read the callback function article and when i cannot get to this sentence, I mean how to explain we alway get id=103?
I have searched the web but cannot find a good answer. Hope here i can get over it. thanks.