3

Consider the following code

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

The question is why this is equal to window inside _go function?

4

1 に答える 1

4

プロパティを呼び出すことによるオブジェクトのバインドは、オブジェクトを直接呼び出す場合にのみ適用されます。プロパティにアクセスして後で呼び出す場合(たとえば、コールバックに渡すなど)、オブジェクトのバインドは保持されません。

動作は次のようになります。

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

Controller.prototype._goあなたの場合、それはまったく同じ関数を参照しているので、あなたも同様に合格することができます。self._go.bind(self)解決策は、バインディングを維持するために使用することです。

于 2012-12-06T11:56:51.937 に答える