2012-05-18 20 views
9

我有一個名爲Foo的類(或函數包含的對象;我聽說沒有像Javascript類那樣的東西),附帶一個事件處理函數點擊事件。當調用事件處理程序時,我想修改我的Foo類的屬性。通常,我會使用this關鍵字,但在事件處理函數中,將this引用設置爲對html元素的引用。這裏是我的代碼:Javascript獲取對事件處理函數的父對象/類的引用

function Foo() { 

    this.num=0; 
    $('element').click(this.eventHandler);// jQuery to attach an onclick event to my element. 

    this.eventHandler=function() { 
     this.num++;// This doesn't work. 
     // Normally, "this" would refer to my instance of Foo, 
     // but as an event handler, "this" refers to the html element. 
    } 
} 

所以我的問題是:我怎麼得到我的Foo實例的引用到我的事件處理程序,這樣我可以修改它的屬性(如num)?

回答

13
function Foo() { 
    var _self = this; 
    this.num=0; 

    $('element').click(this.eventHandler);// jQuery to attach an onclick event to my element. 

    this.eventHandler=function() { 
     _self.num++; 
    } 
} 

使用外部範圍

+1

如果需要釋放對象,該解決方案是否會導致內存泄漏? –

1

你可以存儲在你可以在你的事件處理程序訪問構造函數this參考定義的參考_self = this

function Foo() { 

    this.num=0; 
    $('element').click(this.eventHandler);// jQuery to attach an onclick event to my element. 

    var that = this; 
    this.eventHandler=function() { 
     that.num++;// This doesn't work. 
    } 
} 
13

您需要綁定函數的上下文;否則this將是全局對象:

$('element').click($.proxy(this.eventHandler, this)); 

在現代瀏覽器,您還可以使用Function.prototype.bind

$('element').click(this.eventHandler.bind(this)) 
+0

這應該是被接受的答案。它更強大,因爲關閉並不總是一種選擇。 –

2
function Foo() { 
    this.num=0; 
    $(document).on('click', 'element', this, this.eventHandler); 
    this.eventHandler=function(e) { 
     var _this = e.data; 
     _this.num++; 
    } 
} 

1)使用jQuery()方法來連接事件偵聽器。 2)使用引用_this來訪問父類。