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

czu*_*zuk 2 jquery jquery-callback

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

伪类构造函数的代码

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`?
  });

}
Run Code Online (Sandbox Code Playgroud)

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

Kai*_*Kai 13

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

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

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

}
Run Code Online (Sandbox Code Playgroud)


小智 8

这在jQuery API中有更好的记录.jQuery Bind

$ .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
}
Run Code Online (Sandbox Code Playgroud)

我希望这有帮助!