Javascript setters/getters
- by Martin Hansen
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);