【问题标题】:How can you access a javascript class property inside of an anonymous function is the same class如何访问匿名函数内部的 javascript 类属性是同一个类
【发布时间】:2017-12-18 15:22:05
【问题描述】:

我有一个 javascript (es2015) 类,我想在 $.each 调用的函数中更新数组的值。但是在 build myarr 中是未定义的。我假设thiseach 函数内引用传递给each 的匿名函数。如何访问myarr的类实例?

class mycl{
  constructor(){
     this.myarr=[];
  }
  build(d){
    $.each(d,function(d,i){
      let myd = ..... // Do some stuff with the data
      this.myarr.push(myd);      
    });
  }
}

【问题讨论】:

  • push[myd] 应该是push(myd)
  • 在每个like var self=this;之前将类实例绑定在一个变量中;
  • @jmargolisvt.. 比错字更正。
  • @AnamulHasan。谢谢,效果很好。

标签: javascript class properties scope


【解决方案1】:

您是否尝试过在每个函数中使用绑定?像这样:

class mycl{

  constructor(){
     this.myarr=[];
  }
  build(d){
    $.each(d,function(d,i){
      let myd = ..... // Do some stuff with the data
      this.myarr.push[myd];      
    }).bind(this);
  }
}

【讨论】:

    【解决方案2】:

    您需要在变量中保留对类的引用,如下所示:

    class mycl{
      constructor(){
        this.myarr=[];
      }
      build(d){
        const self = this; //keep a reference to the class here and use it to access class attributes.
        $.each(d,function(d,i){
          let myd = ..... // Do some stuff with the data
          self.myarr.push(myd);      
        });
     }
    }
    

    【讨论】:

      【解决方案3】:

      创建一个作为 Mycl 函数的构建器函数并调用它而不是使用匿名函数。

      class mycl{
        constructor(){
           this.myarr=[];
        }
        builder(d,i){
            // let myd = ..... // Do some stuff with the data
            this.myarr.push(myd);      
        },
        build(d){ $.each(d,this.builder);  }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-12-31
        相关资源
        最近更新 更多