Function 函数内部无法识别“this”
我定义了一个属性,但当我试图从setInterval匿名函数中访问它时,它无法被识别Function 函数内部无法识别“this”,function,typescript,Function,Typescript,我定义了一个属性,但当我试图从setInterval匿名函数中访问它时,它无法被识别 this.game.seconds = 6; useTimer() { let timer = setInterval( function () { this.game.seconds--;//here the keyword this is not being recognized }, 1000 ); } 出现此问题的原因是您没有使用箭头
this.game.seconds = 6;
useTimer() {
let timer = setInterval(
function () {
this.game.seconds--;//here the keyword this is not being recognized
}, 1000
);
}
出现此问题的原因是您没有使用箭头函数 Arrow函数从其外部执行上下文中获取这一点 报告提到: 箭头函数确实提供了自己的绑定,但它仍然保留 这个值是封闭词法上下文的值 阅读更多信息 因此,请注意这一点:
let timer = setInterval(
() => {
this.game.seconds--; // 'this' takes its value from the outer context
}, 1000
);
我可以用Dummy评论的箭头函数实现我的目标,gsamaras回答:
this.game.seconds = 6;
useTimer() {
let timer = setInterval(
() => {
this.game.seconds--;
}, 1000
);
}
更多信息。提示可能重复:这是因为您没有使用箭头功能。这与TypeScript无关。您正在使用的语言称为JavaScript。TypeScript仅仅是JavaScript之上的一个薄薄的类型层。TypeScript没有为此引入新的语义;事实上,它没有引入任何新的执行语义。