Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/470.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何访问匿名函数中的javascript类属性是同一个类_Javascript_Class_Properties_Scope - Fatal编程技术网

如何访问匿名函数中的javascript类属性是同一个类

如何访问匿名函数中的javascript类属性是同一个类,javascript,class,properties,scope,Javascript,Class,Properties,Scope,我有一个javascript(es2015)类,我想更新$each调用的函数中数组的值。但是,内置myarr未定义。我假设此在中,每个函数都引用传递给每个的匿名函数。我如何访问myarr的课程设置 class mycl{ constructor(){ this.myarr=[]; } build(d){ $.each(d,function(d,i){ let myd = ..... // Do some stuff with the data

我有一个javascript(es2015)类,我想更新$each调用的函数中数组的值。但是,内置myarr未定义。我假设
中,每个
函数都引用传递给
每个
的匿名函数。我如何访问
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);      
    });
  }
}

创建一个生成器函数,它是Mycl的函数,并调用它,而不是使用anon函数

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

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

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

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

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

push[myd]
应该是
push(myd)
在每个like var self=this之前将类实例绑定到变量中@jmargolisvt。。阿纳穆尔哈桑:谢谢你的错字更正。谢谢,效果很好。