JS class method in a setInterval doesn't work [duplicate]

亡梦爱人 提交于 2019-12-20 03:26:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!