类变量在函数内未定义

alg*_*edi 3 function settimeout typescript angular8

只是想学习 Angular 2+(特别是 8),对于我的一生,我无法理解为什么类变量在类函数内是“未定义”的,但如果我用 ES6 风格编写函数则可以访问。

我尝试在构造函数中设置,但这没有意义。

export class GameControlComponent implements OnInit {

    myVar;
    counter = 0; 

    constructor() {}  ngOnInit() {}

    handleClickStart() {

        this.myVar = setInterval(this.myFunc, 1500);
    }

    myFunc() {
        this.counter++;
        console.log(this.counter);  
    }
}
Run Code Online (Sandbox Code Playgroud)

调用“handleClickStart”后,每 1.5 秒输出 NaN。为什么????我本来期望1 2 3......

以这种方式实现handleClickStart给了我想要的结果:

handleClickStart() {    
    this.myVar = setInterval(() => {
      console.log(this.counter + 1);
      this.counter++;
    }, 1500);
}
Run Code Online (Sandbox Code Playgroud)

但仍然不明白为什么第一种方法没有成功。

Seb*_*min 6

this此行为与作用域、箭头函数以及 Javascript 函数/对象的工作方式有关。

JavaScript 中的函数在特定上下文中运行,并使用this访问当前上下文。this.counter示例代码中的函数内部不可用/定义setInterval(),因此我们得到undefined.

现在,在箭头函数中,事情很特殊/不同。箭头函数总是在词法上绑定上下文(词法范围意味着它this从包含箭头函数的代码中使用。),因此this将引用原始上下文,即类。

一个更简单的例子可能会更清楚。

const obj = {
  myVar: 'foo',
  myFunc: function() { 
    console.log('Actual Variable value: ',this.myVar)  

    setTimeout(() => {
      console.log('Set timeout using Arrow function: ',this.myVar)
    }, 1000);
    setTimeout(function () {
      console.log('Set timeout using Normal function: ',this.myVar)
    }, 1000);
  }
}
obj.myFunc();
Run Code Online (Sandbox Code Playgroud)

输出

Actual Variable value: foo
Set timeout using Arrow function:  foo
Set timeout using Normal function:  undefined
Run Code Online (Sandbox Code Playgroud)

阅读更多

  1. 箭头功能
  2. 这个关键字