Wanderer
Wanderer

Reputation: 590

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

Upvotes: 0

Views: 1107

Answers (3)

Hugo sama
Hugo sama

Reputation: 909

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

Upvotes: 1

Robert Fines
Robert Fines

Reputation: 720

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

Upvotes: 0

Blindman67
Blindman67

Reputation: 54059

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

Upvotes: 0

Related Questions