从jQuery中的回调函数引用对象 [英] Reference to an object from a callback function in jQuery
本文介绍了从jQuery中的回调函数引用对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下情况.在伪类的构造函数中,我将click事件附加到元素上.触发事件后,我想从回调函数中引用设置事件的对象.
I have following situation. In a constructor of a pseudo class I attach a click event to an element. When the event is triggered I would like to refer from the callback function to the object where the event was set.
伪类构造函数的代码
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`?
});
}
如何在没有全局变量的情况下引用对象?
How to refer to the object without an global variable?
推荐答案
在Javascript中,匿名函数能够引用在函数创建范围内存在的所有变量.由于this
在回调函数中被重新分配,因此您可以在输入回调之前创建一个本地变量来存储它.
In Javascript an anonymous function is able to reference all variables that existed at the scope of the function's creation. Since this
gets reassigned in the callback function, you can create a local variable to store it before you enter the callback.
function MyClass(){
this.myClassAttribute = "A class attribute";
var myClass = this;
$("span").click(function(){
myClass.myClassAttribute = "hello";
});
}
这篇关于从jQuery中的回调函数引用对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文