javascript – 匿名函数里面的“this”?

在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;
            };
        })();
    }
}

问题是当我尝试实例化上述对象时,动态方法被附加到窗口对象而不是实例化的对象.似乎“这个”指的是窗口.

// 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不是函数”.

为实例化的每个对象生成动态函数的正确方法是什么?

这本书是代码吗?我有这本书,但我还没读完.

这本书中的错误.检查勘误表:http://www.apress.com/9781590597279

在匿名函数内部,这是全局窗口.

你可以通过在它之后添加.call(this,i)来使它工作.

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(i) {
            // 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;
            };
        }).call(this, i);
    }
} 
https://stackoverflow.com/questions/9551932/this-inside-an-anonymous-function

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:javascript – 匿名函数里面的“this”?