var author = {
firstname: 'Martin',
lastname: 'Hansen'
}
function settersGetters(propStr) {
for (var i = 0; i < propStr.length; i++) {
author['_'+ propStr[i]] = null;
author.__defineGetter__(propStr[i],
function() {
return author['_'+ propStr[i]];
});
author.__defineSetter__(propStr[i],
function(val) {
author['_'+ propStr[i]] = val;
});
};
}
The above code would hopefully generate setters/getters for any supplied properties (in an array) for the object author.
But when I call the below code Both firstname and lastname is olsen.. What am I doing wrong?
settersGetters(['firstname', 'lastname']);
author.firstname = 'per';
author.lastname = 'olsen';
console.log(author.firstname);
console.log(author.lastname);
asked Mar 12, 2010 at 14:01
Martin Hansen
5,2543 gold badges35 silver badges53 bronze badges
2 Answers 2
I suspect this is a closure issue, which several helpful people explained to me here.
Try wrapping the i reference inside a function, and read up on closures. Despite all the help, I confess that I still don't really understand them.
answered Mar 12, 2010 at 14:09
Carl Manaster
40.5k17 gold badges109 silver badges158 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
T.J. Crowder
It is indeed, when the generated functions are called, they'll always have the highest
i value. More: blog.niftysnippets.org/2008/02/… The definition is made in a closure, so all the setters are using the last value of i.
Use this instead:
function setterGetter(property)
{
author['_'+ property] = null;
author.__defineGetter__(property,
function() {
return author['_'+ property];
});
author.__defineSetter__(property,
function(val) {
author['_'+ property] = val;
});
}
function settersGetters(propStr) {
for (var i = 0; i < propStr.length; i++) {
setterGetter(propStr[i]);
};
}
answered Mar 12, 2010 at 14:15
AlfonsoML
12.7k2 gold badges49 silver badges55 bronze badges
Comments
lang-js