2009-10-16 55 views
2

我有以下情況。在僞類的構造函數中,我將一個單擊事件附加到一個元素。當事件被觸發時,我想從回調函數中引用設置事件的對象。從jQuery中的回調函數引用對象

碼僞類的構造函數

function MyClass(){ 
    this.myClassAttribute = "A class attribute"; 

    // here `this` refers to the object 

    $("span").click(function(){ 
    // here `this` refer to a matched element, i.e. "span" 
    // How to get the value of `myClassAttribute`? 
    }); 

} 

如何引用對象沒有全局變量?

回答

12

在Javascript中,匿名函數能夠引用存在於函數創建範圍內的所有變量。由於this在回調函數中被重新分配,您可以在輸入回調之前創建一個本地變量來存儲它。

function MyClass(){ 
    this.myClassAttribute = "A class attribute"; 
    var myClass = this; 

    $("span").click(function(){ 
    myClass.myClassAttribute = "hello"; 
    }); 

} 
+0

您的點擊處理函數是一個閉包,它們是javascript http://www.google.com/search?q=javascript+closures的強大部分 – JeremyWeir 2009-10-16 18:46:38

+0

我知道這已經有幾年了。但是我遇到了這個解決方案的問題。如果你有幾個類實例,最好使用@Stephen Delano提供的答案。因爲myClass將始終包含已創建的最後一個實例。 – Jodo 2015-11-27 14:55:47

8

這在jQuery API中有更好的記錄。 jQuery Bind

。點擊$僅僅是$ .bind快捷方式( '點擊',/ 沒有數據 /,回調)

$('span').bind('click', { parentObj: this }, function(e) { 
    var parentObj = e.data.parentObj; 
    // the rest of your code goes here 
} 

我希望這有助於!

+0

這是我認爲正確的做法! – nacholibre 2014-01-15 14:05:36