Typescript How to access component variable in foreach loop?

Hey, can someone tell me how can I access the component variable in the foreach loop? Here's 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);
  }

      

+3


source to share


2 answers


If you use function (e)

, this

inside it will reference the function scope instead of the class.

Use Arrow Function

(or Fat Arrow

) instead :

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

      



If there is only one parameter, you can also omit the parenthesis around it:

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

      

Here is a good article explaining its behavior: https://basarat.gitbooks.io/typescript/docs/arrow-functions.html

+13


source


The meaning this

depends on the scope you are in. Consider how to do it:



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

      

+4


source







All Articles