2017-01-20 11 views
3

试图创建打字稿定时器循环:打字稿的setTimeout循环通过这个错误

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

但第一循环正常工作后,我得到这个错误:“遗漏的类型错误:this.timeout不是一个函数”。看起来这个变量在初始循环后不存在。有任何想法吗?

+2

如果使用箭头函数('=>')代替'function'那么'this'上下文将嵌套函数内自动捕捉。有用的文档:https://basarat.gitbooks.io/typescript/content/docs/arrow-functions.html和https://www.typescriptlang.org/docs/handbook/functions.html – JBC

回答

4

由于这种情况下丢失。使用箭头功能更好。

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

因为您的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();

或者你可以用lambda functions工作,这将保持this到对象。 Lamdathis将引用外部的this,它调用lambda函数。

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

 

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