Typescript 类变量未在函数中定义
我只是想学习Angular 2+(特别是8),就我的一生而言,我不明白为什么类变量在类函数中是“未定义”的,但如果我用ES6风格编写函数,它是可以访问的 我尝试在构造函数中设置,但这没有意义Typescript 类变量未在函数中定义,typescript,function,settimeout,angular8,Typescript,Function,Settimeout,Angular8,我只是想学习Angular 2+(特别是8),就我的一生而言,我不明白为什么类变量在类函数中是“未定义”的,但如果我用ES6风格编写函数,它是可以访问的 我尝试在构造函数中设置,但这没有意义 export class GameControlComponent implements OnInit { myVar; counter = 0; constructor() {} ngOnInit() {} handleClickStart() {
export class GameControlComponent implements OnInit {
myVar;
counter = 0;
constructor() {} ngOnInit() {}
handleClickStart() {
this.myVar = setInterval(this.myFunc, 1500);
}
myFunc() {
this.counter++;
console.log(this.counter);
}
}
调用“handleClickStart”后,每1.5秒输出一次NaN。为什么?
我本以为会有123
通过这种方式实现handleClickStart,可以获得预期的结果:
handleClickStart() {
this.myVar = setInterval(() => {
console.log(this.counter + 1);
this.counter++;
}, 1500);
}
但是仍然无法理解为什么第一种方法不起作用。这种行为与作用域、箭头函数、
以及Javascript函数/对象的工作方式有关
JavaScript中的函数在特定上下文中运行,并使用此
访问当前上下文<示例代码中的code>this.counter
在setInterval()函数中不可用/未定义,因此我们得到未定义的
现在,在箭头函数中,事情是特殊的/不同的。Arrow函数始终以词汇形式绑定上下文(词汇范围表示它使用包含Arrow函数的代码中的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();
输出
Actual Variable value: foo
Set timeout using Arrow function: foo
Set timeout using Normal function: undefined
阅读更多
可能重复的