【发布时间】: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