传递此错误的TypeScript setTimeout循环

Ben*_*ard 8 javascript timeout class function typescript

尝试在TypeScript中创建一个计时器循环:

timeout() {
    setTimeout(function () {
        console.log('Test');
        this.timeout();
    }, 1000/60);
}
Run Code Online (Sandbox Code Playgroud)

但是在第一个循环正常工作后我得到了这个错误:"未捕获的TypeError:this.timeout不是函数".看起来这个变量在初始循环后不存在.有任何想法吗?

Sur*_*yan 29

因为你this没有引用该对象.每个功能都有自己的功能.所以你this的内容是由匿名函数定义的setTimeout().

要使程序正常工作,您需要this在超时之前保持并使用该变量.

class Test {
  
  timeout() {
      var that = this;
      setTimeout(function () {
          console.log('Test');
          that.timeout();
      }, 1000/60);
  } 
  
}


let t = new Test();
t.timeout();
Run Code Online (Sandbox Code Playgroud)

或者你可以使用lambda functions,这将保持this你的对象.Lamdathis将指外的this,这称之为拉姆达function`.

class Test {
      
   timeout() {
       setTimeout(() => {
           console.log('Test');
           this.timeout();
       }, 1000/60);
   } 
      
}


let t = new Test();
t.timeout();
Run Code Online (Sandbox Code Playgroud)


Smi*_*nin 9

因为这种背景丢失了.使用箭头功能这是更好的.

timeout() {
    setTimeout(() => {
        console.log('Test');
        this.timeout();
    }, 1000/60);
}
Run Code Online (Sandbox Code Playgroud)