函数"/>
未在nodeJS类的setInterval和开关/案例中定义函数
我想创建一个类,如果某个变量具有某个值,则可以使用setInterval()
函数在其中创建一个间隔。作为处理程序,我放入了预定义的函数,但是,当尝试运行代码时,它表示未定义函数。这是代码。
class Bot {
i = 0;
constructor() {
switch (this.i) {
case 0:
this.interval = setInterval(this.foo, 1000);
break;
}
}
foo = () => {
console.log("hi")
};
//Other Syntaxes I tried without luck:
foo = function() {
console.log("hi");
}
function foo() {
console.log("hi");
}
foo() {
console.log("hi");
}
//I also tried first defining the function, and then creating a constructor
}
回答如下:class Bot {
i = 0;
constructor() {
switch (this.i) {
case 0:
this.interval = setInterval(this.foo, 1000);
break;
}
}
foo = function() {
console.log("hi");
}
}
const b = new Bot();
这对我有用。但是它将在创建对象实例new Bot();
之后立即开始间隔如果您要控制间隔,则可以执行以下操作:
class Bot {
i = 0;
constructor() {
switch (this.i) {
case 0:
this.startInterval = () => { this.interval = setInterval(this.foo, 1000); }
break;
}
}
foo = function() {
console.log("hi");
}
}
const b = new Bot(); // Creating new Object instance
b.startInterval(); // start intverval
setTimeout(() => {clearInterval(b.interval)}, 4000); // end interval after 4000 milsec
更多推荐
未在nodeJS类的setInterval和开关/案例中定义函数
发布评论