此关键字是构造函数中的窗口对象

Nat*_*nes 7 javascript this

好吧,所以我认为我理解这一点(没有双关语意),但显然不是.

var Constructor = function () {
    var internalFunction = function () {
        return this === window;
    };
    this.myMethod = function () {
        alert(internalFunction());
    };
};
var myObj = new Constructor();
myObj.myMethod();
Run Code Online (Sandbox Code Playgroud)

这个警报true.为什么内部函数不能this作为对象?相反,我必须用alert(internalFunction.call(this));myMethod.

编辑:我正在寻找解释为什么this以这种方式分配,而不是var self = this;等等的解决方法.抱歉,如果我没有说清楚.

Tim*_*own 6

this在调用函数之前,它不受约束,并且取决于函数的调用方式.您可以将其视为隐式传递给函数的额外参数.

在这种情况下,问题是你正在internalFunction使用internalFunction().该this值是通过调用一个函数作为方法(如在任一设置foo.bar()foo["bar"]()),或通过设置this经由显式call()apply().你的调用都没有,所以this恢复到全局对象.

在保持internalFunction私有的情况下,在这种情况下实现所需的最简单方法是this在构造函数内部存储引用:

var Constructor = function() {
    var thisObj = this;

    var internalFunction = function () {
        return thisObj === window;
    };

    thisObj.myMethod = function () {
        alert(internalFunction());
    };
}
Run Code Online (Sandbox Code Playgroud)