【发布时间】:2016-07-13 22:11:43
【问题描述】:
我是 JavaScript/TypeScript 的新手,我想弄清楚这里发生了什么。
class MyClass {
constructor() {
this.doThisEverySecond();
setInterval(this.doThisEverySecond, 1000); // Tried here
}
doThisEverySecond():void {
console.log("Do some stuff");
this.subroutineForOrganization();
console.log("Do more stuff\n");
}
subroutineForOrganization():void {
console.log("Doing many things");
}
}
const foo:MyClass = new MyClass();
setInterval(foo.doThisEverySecond, 1000); // And tried here
我想调用一个函数 doThisEverySecond() 并让它每 x 秒执行一次;为了简单的组织目的,我将它的一些功能提取到子例程 subroutineForOrganization() 中。
无论我是在其构造函数中还是在实例化后立即调用 setInterval(),我都会收到以下错误:
Do some stuff
Doing many things
Do more stuff
Do some stuff
D:\Webstorm Projects\Sonification\es5\src_ts\test.js:8
this.subroutineForOrganization();
^
TypeError: this.subroutineForOrganization is not a function
at Timeout.MyClass.doThisEverySecond [as _repeat] (D:\Webstorm Projects\Sonification\es5\src_ts\test.js:8:14)
at Timeout.wrapper [as _onTimeout] (timers.js:417:11)
at tryOnTimeout (timers.js:224:11)
at Timer.listOnTimeout (timers.js:198:5)
Process finished with exit code 1
我不明白为什么它在第一次从构造函数调用时运行良好,但在使用 setInterval 调用时却出现错误。那时它是一个怎样的功能,但不是现在?是否有某种我不明白的 JavaScript 作用域魔法?
谢谢!
已解决:使用箭头函数调用(如下所述)保留对 this (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this) 的引用
【问题讨论】:
-
this不是你想的那样。 -
按照上面链接的帖子,这就是最终的工作。我需要做的就是将调用包装在一个匿名函数中。是时候阅读闭包了...
setInterval(() => this.doThisEverySecond(), 1000);
标签: javascript node.js typescript