2012-12-06 3 views
3

다음 코드자바 스크립트 :이 변수 및 콜백

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_go 함수 내에서 window 같다 왜 질문은?

답변

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)을 사용하여 바인딩을 유지하는 것입니다.