javascript:这个变量和回调

Eug*_*y89 4 javascript

考虑下面的代码

Class.prototype.init = function() {
    var self = this;
    var onComplete = function() {
        self.a.doSomethingElse(self._go);
    };

    console.log(this); //prints Object {...}
    this.a.doSomething(onComplete); //onComplete is called inside a
};

Controller.prototype._go = function(map) {
    console.log(this); //prints 'Window'
};
Run Code Online (Sandbox Code Playgroud)

问题是为什么this等于window内部_go函数?

pim*_*vdb 5

通过调用属性来绑定对象仅适用于直接调用它的情况。当仅访问该属性并稍后调用它时(例如将其传递给回调),不会保留对象绑定。

该行为归结为以下几点:

var a = {
  b: function() {
    console.log(this);
  }
};

a.b(); // logs a, because called directly

var func = a.b;
func(); // logs window, because not called directly
Run Code Online (Sandbox Code Playgroud)

就您而言,您也可以通过,Controller.prototype._go因为它引用了完全相同的函数。解决办法是使用self._go.bind(self)保持绑定。