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;
});
};
}
上面的代碼會希望爲對象作者提供的任何屬性(在數組中)生成setter/getters。Javascript setter/getters
但是當我調用下面的代碼名字和姓氏都是奧爾森..我做錯了什麼?
settersGetters(['firstname', 'lastname']);
author.firstname = 'per';
author.lastname = 'olsen';
console.log(author.firstname);
console.log(author.lastname);
謝謝,解決了它。 – 2010-03-12 15:28:14