Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript How to access component variable in foreach loop?

Hey can somebody tell me how I can access a component variable in foreach loop ? Here my Plunker

 public testVariable:number;

  test(){
    console.log('fired');
    var x  =[1,2,3,4];

    x.forEach(function (e){
      this.testVariable = e;
    })

    console.log( this.testVariable);
  }
like image 222
Przemysław Zamorski Avatar asked Jun 01 '17 09:06

Przemysław Zamorski


2 Answers

If you use function (e), the this inside it will refer to the function's scope instead of the class.

Use the Arrow Function(or Fat Arrow) instead:

x.forEach((e) => {
    this.testVariable = e;
})

When having only 1 parameter, you may also omit the parenthesis around it:

x.forEach(e => {
    this.testVariable = e;
})

Here's a good article explaining it's behavior: https://basarat.gitbooks.io/typescript/docs/arrow-functions.html

like image 135
borislemke Avatar answered Oct 19 '22 19:10

borislemke


The value of this depends on the scope you're in. Consider doing it like this:

public testVariable:number;

test(){
    console.log('fired');
    var x  =[1,2,3,4];

    var self = this;
    x.forEach(function (e){
        self.testVariable = e;
    })

    console.log( this.testVariable);
}
like image 45
Halcyon Avatar answered Oct 19 '22 18:10

Halcyon