我有一個關於在一個對象中維護this
的範圍的一般性問題。這裏有一個簡單的代碼片段。請注意0一行,並在事件處理程序中呼叫that.showMenu()
。維護範圍
var MyObj = {
init : function(target){
this.$Target = $(target);
this.$Menu = $(target).find('.menu');
this.eventBindings();
},
eventBindings : function(){
var that = this;
this.$Target.on('click', '.anchor', function(e){
e.preventDefault();
that.showMenu();
//some other code
});
},
showMenu : function(){
this.$Menu.show();
}
};
MyObj.init('.myTarget')
代碼應該有點自我解釋。通常我會嘗試在我的eventBindings()
之外創建可重用的方法。我不斷遇到的問題是通過this
,這將參考MyObj
到事件處理程序,所以我可以撥打this.showMenu()
。
爲了克服障礙,我總是將this
分配給一個名爲that
的變量,所以當我進一步縮小範圍時,我有一個參考。但我覺得這不可能是最好的方法...有人可以提出更好的選擇嗎?
對我來說看起來很好,但'那是一個可怕的名字。考慮一些更具描述性的內容,比如'outerScope'。 – 2013-04-11 21:27:23
另請參閱函數原型上的[.bind()'方法](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind)。 – Pointy 2013-04-11 21:28:03
@RobertHarvey儘管如此,多年來這種'這個'是如何被普遍使用的,這不是很有趣嗎? ;) – summea 2013-04-11 21:53:50