我正在学习如何在Javascript中创建getter和setter,我的代码如下:
// Create a new User object that accept an object of properties
function User(properties) {
// Iterate through the properties of the object, and make
// sure it's properly scoped
for (var i in properties) { (function(){
// Create a new getter for the property
this['get' + i] = function() {
return properties[i];
};
// Create a new setter for the property
this['set' + i] = function(val) {
properties[i] = val;
};
})(); }
}
// Create a new User object instance and pass in an object of
// properties to seed it with
var user = new User({
name: 'Bob',
age: 28
});
// Just note that the name property does not exist, as it's private
// within the property object
console.log(user.name == null);
// However, we are able to access its value using the new getname()
// method, that was dynamically generated
console.log(user.getname());
然而,控制台显示错误,说用户没有getname方法。代码试图动态生成getter和setter方法,我认为看起来没问题。您有什么想法吗?
this
,请在循环外部执行var t = this;
并在内部引用t
。 - Paul S.properties
被隐藏了,但这并不是相关的。 - beatgammit