3

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

伪类构造函数代码

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

}

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

4

3 回答 3

14

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

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

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

}
于 2009-10-16T18:39:55.967 回答
8

这在 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
}

我希望这有帮助!

于 2009-10-16T18:43:54.760 回答
0

我使用 jQuery $get 遇到了同样的问题。传递的回调函数实际上是一个类函数,因此您无权访问特定的实例数据。

我想这是 Javascript 语言的限制,它不将对象函数作为回调参数处理。

我使用类似的解决方法解决了:

class customer {

    constructor() {
        this.customerName ="";
    }

    getCustomerName() {
        let dataRequest = {
            url: '/getCustomerName',
            data: {
                customerId: '035'
            },
            dataType: "json"
        };
        var thisObject = this;
        $.get(dataRequest).done(
            function(dbD) { thisObject.queryData(dbD,thisObject)}
        );
    }

    queryData(dbData,obj) {
        obj.customerName = dbData[0];
    }
}

于 2021-05-23T16:37:49.650 回答