1

So This is a pomodoro clock. When I call the inter method (who call countdown every 1s) this.work return undefined and I don't know why. If I call the property from outside the class (t1.work for eg) it's defined, but calling it from inside countdown (this.work) won't work. Anyone knows why?

class Timer {

  //constructor de la clase, se definen las propiedades  
  constructor(work, rest) {
    this.work = work;
    this.rest = rest;
    this.interval = undefined;
  }

  //countdown method (dhu)
  countdown(){
    if (this.work >= 0) {
      console.log(this.work);
      this.work -= 1;
      return;
    } else {
      console.log(this.rest);
      (this.rest > 0) ? this.rest -= 1 : clearInterval(this.interval);
    }
  }

  //interval to invoque countdown method every second
  inter(){
    this.interval = setInterval(this.countdown, 1000);
  }

}

//Creating an object with the timer class, passing values.
var t1 = new Timer(5, 3);

//Calling the method inside object t1
t1.inter();

At first, I thought it was an If problem, but tried to do a simple console.log(this.work) And didn't work either. Thanks

Chantun
  • 81
  • 1
  • 7
  • 1
    Possible duplicate of [Javascript setInterval and \`this\` solution](https://stackoverflow.com/questions/2749244/javascript-setinterval-and-this-solution) – Ele Feb 17 '18 at 11:28
  • 1
    In the constructor add the line `this.inter = this.inter.bind(this);`.Do the same for the other methods that use `this` too. – Andy Feb 17 '18 at 11:31
  • Hooo thanks!!! So the problem was that inside the inter method "this" refers to the method perse? – Chantun Feb 17 '18 at 11:40

1 Answers1

2

In your case you are not binding this to current context inside the setInterval function

just bind this when call function from setInterval -

this.countdown.bind(this),

class Timer {

  //constructor de la clase, se definen las propiedades  
  constructor(work, rest) {
    this.work = work;
    this.rest = rest;
    this.interval = undefined;
  }

  //countdown method (dhu)
  countdown(){
    if (this.work >= 0) {
      console.log(this.work);
      this.work -= 1;
      return;
    } else {
      console.log(this.rest);
      (this.rest > 0) ? this.rest -= 1 : clearInterval(this.interval);
    }
  }

  //interval to invoque countdown method every second
  inter(){
    this.interval = setInterval(this.countdown.bind(this), 1000);
  }

}

//Creating an object with the timer class, passing values.
var t1 = new Timer(5, 3);

//Calling the method inside object t1
t1.inter();
Mamun
  • 66,969
  • 9
  • 47
  • 59
Devraj verma
  • 407
  • 3
  • 14
  • 1
    Thanks! So the problem was that inside the inter method "this" refers to the method scope and not the class scope? – Chantun Feb 17 '18 at 11:49