1
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

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

It is indeed, when the generated functions are called, they'll always have the highest i value. More: blog.niftysnippets.org/2008/02/…
1

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.