“这个"在匿名函数中? [英] "this" inside an anonymous function?

查看:24
本文介绍了“这个"在匿名函数中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 John Resig 的Pro Javascript 技术"一书中,他描述了一种使用以下代码生成动态对象方法的方法:

Inside John Resig's book "Pro Javascript techniques" he describes a way of generating dynamic object methods with the below code:

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

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

The problem is when I try instantiating the above object, the dynamic methods are being attached to the window object instead of the object instantiated. It seems like "this" is referring to the window.

// 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".

Running the above code throws this error "user.getname is not a function".

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

What is the correct way of generating the dynamic functions for each object instantiated?

推荐答案

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

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

It's an error in the book. Check the errata: http://www.apress.com/9781590597279

在匿名函数内部,this是全局的window.

Inside the anonymous function, this is the global window.

您可以通过在其后添加 .call(this, i) 使其工作.

You could make it work by adding .call(this, i) after it.

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

这篇关于“这个"在匿名函数中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆