typescript window.setInterval()无法正常工作

ann*_*iid 2 javascript typescript

我遇到了window.setInterval()方法的问题.下面是一个结构示例,重复调用方法"repeat",但是我不能在"repeat"中调用任何方法.在我实例化管理器(让m = new manager())的示例中,它将打印"Before Print",但不会从printStuff方法或"After Print"消息中打印出日志.

有谁知道为什么会这样?显然这不是我的实际代码,因为它很简单,不能在单独的函数中,但是我的实际代码需要在"repeat"函数中调用许多函数,并且当它找到对另一个函数的调用时它将停止执行.

class manager{

constructor(){
    window.setInterval(this.repeat, 5000);
}

repeat(){
    console.log("Before Print");
    this.printStuff();
    console.log("After Print");
}

printStuff(){
    console.log("Print Stuff");
}
Run Code Online (Sandbox Code Playgroud)

Day*_*eon 10

设置间隔将采用this.repeat取出您需要显式"绑定"方法的上下文

setInterval(this.repeat.bind(this), 5000)

要么

setInterval(()=>this.repeat(), 5000)