TypeScript setTimeout循环传递此错误 [英] TypeScript setTimeout loop passing this error

查看:64
本文介绍了TypeScript setTimeout循环传递此错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Trying to create a timer loop in TypeScript:

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

但是在第一个循环正常工作后,我得到以下错误:未捕获的TypeError:this.timeout不是函数".似乎此变量在初始循环后不存在.有什么想法吗?

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没有引用该对象.每个功能都有它自己的.因此,您的thissetTimeout()内部由匿名函数定义的那个.

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

要使您的程序正常工作,您需要在超时前按住this并使用该变量.

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

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


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

或者您可以使用lambda functions来将this保留在对象上.Lamdathis将引用外部的this,后者将调用lambda函数.

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

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


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

这篇关于TypeScript setTimeout循环传递此错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆