首页 > 解决方案 > 模块导出类和函数

问题描述

有一个视觉类:

class Visual {
    constructor() {...}
    async fun1() {...}
    async fun2() {...}
}
module.exports = Visual;

在这里一切正常。但是,我需要fun1根据fun2.

首先,我尝试以“正常”方式使用它,但表示未定义该功能。

async fun1() {
    const result = await fun2();
    ...
}

所以我尝试了另一种方法,通过导出将函数移到类之外。

    class Visual {
        constructor() {...}
        async fun1() {
               const result = await fun2();
               ...
        }
    }
    module.exports = Visual;
    module.exports = {
        fun2: async function () {...}
    };

代码检查器不再说 fun2 没有定义,但是当创建新的 Visual 时,它说它不是构造函数。

const visual = new Visual();

是不是导出的方式不对?我该如何解决?

标签: javascriptnode.jsmodule.exports

解决方案


当您想在 javascript 中使用同一个类中的另一个类中的一个方法时,您必须在它前面加上 this。

const result = await fun2();变得如此const result = await this.fun2();


推荐阅读