Javascript TypeScript setTimeout 循环传递了这个错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41763518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:37:07  来源:igfitidea点击:

TypeScript setTimeout loop passing this error

javascriptfunctionclasstypescripttimeout

提问by Ben Hayward

Trying to create a timer loop in TypeScript:

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

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

But after the first loop works correctly I'm getting this error: "Uncaught TypeError: this.timeout is not a function". It seems that the this variable does not exist after the initial loop. Any ideas?

但是在第一个循环正常工作后,我收到此错误:“未捕获的类型错误:this.timeout 不是函数”。似乎在初始循环之后 this 变量不存在。有任何想法吗?

回答by Suren Srapyan

Because your thisdoesn't refer to the object. Every function has it's own this. So your thisis the one which is defined by anonymous function inside the setTimeout().

因为你的this不是指对象。每个函数都有它自己的 this。所以你this是由匿名函数在setTimeout().

To make your program work, you need to hold the thisbefore the timeout and use throught that variable.

为了使您的程序工作,您需要this在超时之前保持并使用该变量。

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


let t = new Test();
t.timeout();

Or you can work with lambda functions, which will keep the thisto your object.Lamda's thiswill refer to the outer's this, which call the lambda function`.

或者您可以使用lambda functions,这将保留this您的对象。Lamda'sthis将引用外部的this,它调用 lambda 函数` 。

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


let t = new Test();
t.timeout();

回答by Smiranin

Because of this context is lost. Use the arrow function this is better.

因为这个上下文丢失了。使用箭头函数这个更好。

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