我正在尝试创建一个对象,该对象动态地构建自己的getter和setter方法:
function Person( properties ) { // 'properties' is an object literal
this._private = properties; // private by convention
for ( key in this._private ) {
this[key] = function() {
return this._private[key];
}
}
}
我希望这会创建如下内容:
var jack = new Person({
working:true,
age:33,
gender:'male'
});
jack.working() --> true
jack.age() --> 33
jack.gender() --> 'male'
问题是,它总是返回'male',如下所示:
jack.working() --> 'male'
jack.age() --> 'male'
jack.gender() --> 'male'
我想念什么? 哦,这只是一个概念证明。我知道这不是在JavaScript中创建getter和setter的完美解决方案。
最佳答案
您遇到了一个经典的范围界定问题。创建一个新函数以围绕key
创建范围:
function Person(properties) { // 'properties' is an object literal
var key;
this._private = properties; // private by convention
this.buildGetter = function (key) {
this[key] = function () {
return this._private[key];
}
};
for (key in this._private) {
this.buildGetter(key);
}
}
示例: http://jsfiddle.net/SEujb/
关于javascript - 动态Getter和Setters-为什么不起作用?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13592527/