2012-05-15 89 views
2

我已經定義在JavaScript中的一類具有一個方法jQuery的事件時,在JavaScript類重寫:「這個」關鍵字處理

function MyClass(text) { 
    this.text = text; 
} 

MyClass.prototype.showText = function() { 
    alert(this.text); 
} 

然後,我定義充當一個click事件處理程序的方法,使用jQuery:

function MyClass(text) { 
    this.text = text; 
    $('#myButton').click(this.button_click); 
} 

MyClass.prototype.showText = function() { 
    alert(this.text); 
}; 

MyClass.prototype.button_click = function() { 
    this.showText(); 
}; 

當我按一下按鈕,它沒有說:

對象#<HTMLInputElement>有沒有方法「showText」

這似乎是this在jQuery的單擊事件處理程序指的HTML元素本身,它不是指的MyClass對象的實例。

我該如何解決這種情況?可

的jsfiddle:http://jsfiddle.net/wLH8J/

回答

10

這是一個預期的行爲,請嘗試:

function MyClass(text) { 
    var self = this; 

    this.text = text; 
    $('#myButton').click(function() { 
     self.button_click(); 
    }); 
} 

或在新的瀏覽器(使用bind):

function MyClass(text) { 
    this.text = text; 
    $('#myButton').click(this.button_click.bind(this)); 
} 

或使用jQuery proxy

function MyClass(text) { 
    this.text = text; 
    $('#myButton').click($.proxy(this.button_click, this)); 
} 

進一步閱讀:

+0

你釘了它。好答案! –

+0

優秀的Yoshi,我會給它一個去$ .proxy的東西,它看起來像是我的完美解決方案,:-) –

+0

@ antur123不客氣!代理可能是關於瀏覽器兼容性的最安全的選擇。 – Yoshi

2

this是當一個函數被調用來確定,而不是當它被定義。您已將該功能複製到點擊處理程序,因此當它被調用時,它不與MyClassthis相關聯,而不是您想要的。

您需要使用閉包將this的值存儲在其他變量中。

function MyClass(text) { 
    this.text = text; 
    var self = this; 
    var click_handler = function() { self.button_click(); }; 
    $('#myButton').click(click_handler); 
}