问题
I have this simple example with a class with a setInterval that calls main() every 5 seconds. When it comes to call print() it returns me TypeError: this.print is not a function. And I'm really stuck. Why if I call main() without setInterval it works smoothly but with setInterval it fails? It's weird. Any workaround to call main() periodically without this issue?
"use strict";
class test {
constructor() {
this.interval = setInterval(this.main, 5000);
}
print(){
console.log('Teeeessssttt');
}
main(){
this.print();
}
}
const a = new test();
回答1:
You'll need to use bind:
this.interval = setInterval(this.main.bind(this), 5000);
回答2:
You can try setInterval(() => this.main(), 5000) as well. this in JavaScript can differ than what you'd expect the program's source code to suggest. See MDN's take on this.
来源:https://stackoverflow.com/questions/51572081/js-class-method-in-a-setinterval-doesnt-work