English 中文(简体)
提到 j背功能中的物体
原标题:Reference to an object from a callback function in jQuery
  • 时间:2009-10-16 18:36:23
  •  标签:

我有这种情况。 在一名伪装类的构造者中,我附上一件点击事件。 当活动启动时,我要从警示职能中提一下事件的标的。

伪装阶级建筑法

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

}

如何在没有全球变量的情况下提及该目标?

最佳回答

在 Java稿中,匿名功能能够参考功能生成范围内的所有变量。 自this上调回电话功能以来,你可以产生一个地方变数,在进入电话接驳之前加以储存。

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

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

}
问题回答

我在使用j Query 植被方面也面临同样的问题。 电话后继功能实际上是一种班级功能,因此无法查阅具体案例的数据。

I suppose this is a limitation of Javascript languange that does not handle object function as a call back parameter.

我通过类似的工作解决:

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];
    }
}




相关问题
热门标签