views:

90

answers:

2
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);
+2  A: 

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.

Carl Manaster
It is indeed, when the generated functions are called, they'll always have the highest `i` value. More: http://blog.niftysnippets.org/2008/02/closures-are-not-complicated.html
T.J. Crowder
+1  A: 

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]);
};
}
AlfonsoML
Thanks, solved it.
Martin Hansen