0
class Frame {
  constructor() {
    this.init();
  }

  init(){
    setTimeout(function(){this.secondFunction()}, 2000); // DOES NOT WORK
  }

  secondFunction(){
  }
 }

I am trying to call a function of a class from another function of same class. When I call it directly with "this.secondFunction()" then it works fine. But when I move it insode of a setTimeout or a JQuery function, it does not work and throws error "this.secondFunction is not a function". I think this is because the "this" changes to timer object when I call it from setTimeout. What's the correct way to call the function in this scenario?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
Gaurav
  • 1,214
  • 2
  • 17
  • 32

1 Answers1

2

The this inside the setTimeout function isn't what you want. Use an arrow function:

setTimeout(() => {
  this.secondFunction();
}, 2000);

The issue was that the function inside setTimeout was changing the this reference from the new instance to the setTimeout, which wasn't what you wanted. An arrow function inherits its this binding, so it'll work perfectly.

An ES5 equivalent would be to use bind outside of the callback, to change the binding.

setTimeout(function() {
  this.secondFunction();
}.bind(this), 2000);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79