Setting Javascript Definegetter And Definesetter In A Loop
Why does each iteration of this: var o = {}; var foo = [['a',1],['b',2],['c',3],['d',4],['e',5]]; for(var i = 0; i < 5; i++) { o.__defineGetter__(foo[i][0], function() {
Solution 1:
You need to create a function that returns a function that does what you want (this is just because of how closures work in JavaScript). This example should work.
var o = {};
var foo = [['a',1],['b',2],['c',3],['d',4],['e',5]];
var getFunc = function(val){
returnfunction() {
return val;
}
};
for(var i = 0; i < 5; i++)
{
var func = getFunc(foo[i][1]);
o.__defineGetter__(foo[i][0], func);
}
console.info(JSON.stringify(o));
Solution 2:
This is because of the way that closures work. Variables are scoped to the functions they are defined in. There is no such thing as a loop variable (unless you are using a version of JS that has the let
keyword). As a result, at the end of the loop, the value of i
is the same in all of the anonymous functions you defined. You can see this by outputting i
at the end of the loop:
for(var i = 0; i < 5; i++)
{
o.__defineGetter__(foo[i][0], function() {
return foo[i][1];
});
console.info(JSON.stringify(o));
}
console.info(i); //outputs 5
EDIT: As pointed out, this is the same problem, as in this question: JavaScript closure inside loops – simple practical example
Post a Comment for "Setting Javascript Definegetter And Definesetter In A Loop"