简体   繁体   中英

How can you access a javascript class property inside of an anonymous function is the same class

I have a javascript (es2015) class I want to update the values of an array within a function called by $.each. However in build myarr is undefined. I assume this is within the each function is referencing the anonymous function passed to the each . How can I access the class intance of 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);      
    });
  }
}

Have you tried using bind in the each function? like so :

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

Create a builder function that is a function of Mycl and call that rather than use an anon function.

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

You will need to keep a reference to the class in a variable like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM