未在nodeJS类的setInterval和开关/案例中定义函数

编程入门 行业动态 更新时间:2024-10-10 16:15:20

未在nodeJS类的setInterval和开关/案例中定义<a href=https://www.elefans.com/category/jswz/34/1771370.html style=函数"/>

未在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和开关/案例中定义函数

本文发布于:2024-05-07 02:06:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1754092.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   定义   案例   nodeJS   setInterval

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!