[英]Javascript class property return undefined when called with a method
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. 当我调用inter方法(每1秒调用一次倒数)时,this.work返回undefined,我不知道为什么。 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. 如果我从类外部调用属性(例如,t1.work),则已定义该属性,但是从倒数内部(this.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. 起初,我以为这是一个If问题,但是试图做一个简单的console.log(this.work)也不起作用。 Thanks 谢谢
In your case you are not binding this to current context inside the setInterval function 在您的情况下,您未将其绑定到setInterval函数中的当前上下文
just bind this when call function from setInterval - 只需在setInterval的调用函数中绑定此对象-
this.countdown.bind(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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.