2009-10-16 56 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