【发布时间】:2012-03-22 01:21:01
【问题描述】:
在 John Resig 的“Pro Javascript 技术”一书中,他描述了一种使用以下代码生成动态对象方法的方法:
// Create a new user object that accepts an object of properties
function User(properties) {
// Iterate through the properties of the object, and make sure
// that it's properly scoped (as discussed previously)
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;
};
})();
}
}
问题是当我尝试实例化上述对象时,动态方法被附加到窗口对象而不是实例化对象。似乎“this”指的是窗口。
// Create a new user object instance and pass in an object of
// properties to seed it with
var user = new User({
name: "Bob",
age: 44
});
alert( user.getname() );
运行上面的代码会抛出这个错误“user.getname is not a function”。
为每个实例化的对象生成动态函数的正确方法是什么?
【问题讨论】:
-
我确信 John Resig 使用了正确的缩进。
-
这似乎不对。在匿名函数内部,
this是window。 -
@Rocket:你怎么没看到那里的压痕?
-
在非数字属性枚举中使用
i作为键名让我很恼火。
标签: javascript anonymous-function