【问题标题】:Why method of current object in inner function is undefined?为什么内部函数中当前对象的方法未定义?
【发布时间】:2014-12-05 06:49:14
【问题描述】:

在外部函数中,this.foo 是 bar,这正是我所期望的。但是,在内部函数中,this.foo 是未定义的,这非常令人惊讶。有人可以帮我吗?谢谢。

var myObject = {
    foo: "bar",
    func: function () {
        console.log("outer func:  this.foo = " + this.foo);
        (function () {
            console.log("inner func:  this.foo = " + this.foo);
        }());
    }
};
myObject.func();

【问题讨论】:

    标签: javascript


    【解决方案1】:

    在外部函数中,this 引用了 myObject,因此可以正确引用和访问 foo。

    在闭包的内部函数中,this 不再指向 myObject。结果,this.foo 在内部函数中是未定义的(在 ECMA 5 之前,内部函数中的 this 将引用全局窗口对象;而在 ECMA 5 中,内部函数中的 this 将是未定义的。) 为了解决这个问题,我们可以在引用它之前将它存储在像 self 这样的局部变量中。

    var myObject = {
        foo: "bar",
        func: function () {
            var self = this;
            console.log("outer func:  self.foo = " + self.foo);
            (function () {
                console.log("inner func:  self.foo = " + self.foo);
            }());
        }
    };
    myObject.func();
    

    【讨论】:

    • ES5 严格模式 undefined,否则window
    【解决方案2】:

    第一个实现是:

    var myObject = {
        foo: "bar",
        func: function () {
            console.log("outer func:  this.foo = " + this.foo);
            (function (self) {
                console.log("inner func:  self.foo = " + self.foo);
            }(this));
        }
    };
    myObject.func();
    

    第二种实现方式是:

    var myObject = {
        foo: "bar",
        func: function () {
            console.log("outer func: this.foo = " + this.foo);
            (function () {
                console.log("inner func:  this.foo = " + this.foo);
            }.bind(this));
        }
    };
    myObject.func();
    

    【讨论】:

    • 第二个没有真正执行。您只需绑定它,仅此而已。
    • 利奥是对的。第二个没有执行。要执行它,只需将 () 放在它后面。 var myObject = { foo: "bar", func: function () { console.log("outer func: this.foo = " + this.foo); (function () { console.log("inner func: this.foo = " + this.foo); }.bind(this)()); } }; myObject.func();
    • 我错过了括号 () ((
    猜你喜欢
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多