Typescript如何在foreach循环中访问组件变量?

Prz*_*ski 9 javascript typescript angular

嘿,有人可以告诉我如何在foreach循环中访问组件变量吗?我的 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);
  }
Run Code Online (Sandbox Code Playgroud)

bor*_*mke 23

如果你使用function (e),this里面它将引用函数的范围而不是类.

使用Arrow Function(或Fat Arrow)代替:

x.forEach((e) => {
    this.testVariable = e;
})
Run Code Online (Sandbox Code Playgroud)

当只有一个参数时,您也可以省略它周围的括号:

x.forEach(e => {
    this.testVariable = e;
})
Run Code Online (Sandbox Code Playgroud)

这是一篇很好的文章解释它的行为:https://basarat.gitbooks.io/typescript/docs/arrow-functions.html


Hal*_*yon 6

的值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);
}
Run Code Online (Sandbox Code Playgroud)