我是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)的引用
答案 0 :(得分:0)
constructor() {
this.doThisEverySecond();
setInterval(this.doThisEverySecond.bind(this), 1000); // Tried here
}
答案 1 :(得分:-1)
我相信这是因为你没有正确定义你的功能。试试这个:
function doThisEverySecond() {
console.log("Do some stuff");
this.subroutineForOrganization();
console.log("Do more stuff\n");
}
和
function subroutineForOrganization() {
console.log("Doing many things");
}