Question

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);
Was it helpful?

Solution

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]);
};
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top