【问题标题】:Javascript class property return undefined when called with a method使用方法调用时 Javascript 类属性返回未定义
【发布时间】:2018-02-17 11:26:47
【问题描述】:

所以这是一个番茄钟。当我调用 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)也没有成功。谢谢

【问题讨论】:

  • 在构造函数中添加行this.inter = this.inter.bind(this);。对使用this的其他方法也这样做。
  • 太感谢了!!!所以问题是在inter方法内部“this”指的是方法本身?

标签: javascript class constructor properties


【解决方案1】:

在您的情况下,您没有将 this 绑定到 setInterval 函数内的当前上下文

从 setInterval 调用函数时绑定 this -

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

【讨论】:

  • 谢谢!所以问题是在inter方法内部“this”指的是方法范围而不是类范围?
猜你喜欢
  • 2020-08-03
  • 2020-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-14
  • 1970-01-01
  • 1970-01-01
  • 2022-08-20
相关资源
最近更新 更多