Javascript setters/getters

Posted by Martin Hansen on Stack Overflow See other posts from Stack Overflow or by Martin Hansen
Published on 2010-03-12T14:01:05Z Indexed on 2010/03/12 14:07 UTC
Read the original article Hit count: 467

Filed under:
|
|
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);

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about getter