使用方法调用时,Javascript类属性返回undefined

时间:2018-02-17 11:26:47

标签: javascript class constructor properties

所以这是一个番茄钟。当我调用inter方法(每隔1秒调用倒计时)时,this.work返回undefined,我不知道为什么。如果我从类外部调用属性(例如t1.work),它已定义,但从倒计时内(this.work)调用它将不起作用。谁知道为什么?

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();

起初,我认为这是一个If问题,但试图做一个简单的console.log(this.work)并且也没有工作。感谢

1 个答案:

答案 0 :(得分:2)

在你的情况下,你没有将它绑定到setInterval函数

中的当前上下文

在setInterval -

中调用函数时绑定它

<强> this.countdown.bind(本)

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();