当使用方法调用时,Javascript类属性返回undefined
这是一个波莫多罗钟。当我调用inter方法(每1s调用一次倒计时)时,这个.work返回未定义,我不知道为什么。如果我从类外调用属性(t1.work for eg),它是被定义的,但是从内部倒计时(this.work)调用它将不起作用。有人知道为什么吗当使用方法调用时,Javascript类属性返回undefined,javascript,class,constructor,properties,Javascript,Class,Constructor,Properties,这是一个波莫多罗钟。当我调用inter方法(每1s调用一次倒计时)时,这个.work返回未定义,我不知道为什么。如果我从类外调用属性(t1.work for eg),它是被定义的,但是从内部倒计时(this.work)调用它将不起作用。有人知道为什么吗 class Timer { //constructor de la clase, se definen las propiedades constructor(work, rest) { this.work = 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),但也没有成功。谢谢在您的情况下,您没有将其绑定到setInterval函数中的当前上下文 当从setInterval调用函数时,只需绑定此函数- 这个.倒计时.绑定(这个)
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();
构造函数中可能存在的重复添加行
this.inter=this.inter.bind(this)
。对使用此
的其他方法也执行相同操作。谢谢!!!所以问题是在inter方法中“this”指的是perse方法?谢谢!所以问题是在inter方法中“this”指的是方法范围而不是类范围?