从jQuery中的回调函数引用对象

我有以下情况。 在伪类的构造函数中,我将click事件附加到元素。 当事件被触发时,我想从回调函数引用到设置事件的对象。

伪类构造函数的代码

function MyClass(){ this.myClassAttribute = "A class attribute"; // here `this` refers to the object $("span").click(function(){ // here `this` refer to a matched element, ie "span" // How to get the value of `myClassAttribute`? }); } 

如何在没有全局变量的情况下引用对象?

在Javascript中,匿名函数能够引用在函数创建范围内存在的所有变量。 由于this会在回调函数中重新分配,因此您可以在输入回调之前创建一个本地变量来存储它。

 function MyClass(){ this.myClassAttribute = "A class attribute"; var myClass = this; $("span").click(function(){ myClass.myClassAttribute = "hello"; }); } 

这在jQuery API中有更好的记录。 jQuery绑定

$ .click只是$ .bind的快捷方式(’click’,/ no data /,callback)

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

我希望这有帮助!