2012-12-06 21 views
3

考慮下面的代碼的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' 
}; 

問題是,爲什麼this等於window裏面_go功能?

回答

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)來保持綁定。