javascript - 模块导出类和函数
问题描述
有一个视觉类:
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();
是不是导出的方式不对?我该如何解决?
解决方案
当您想在 javascript 中使用同一个类中的另一个类中的一个方法时,您必须在它前面加上 this。
const result = await fun2();
变得如此const result = await this.fun2();
推荐阅读
- jquery - Laravel 5.6 中的日期时间范围搜索
- c# - Onion 架构中的 Dtos
- python - 通过“g”选择熊猫列“a”、“b”和“e”
- python - 如何解析文本中的越南语 unicode 字符
- python - Pandas - 按所有列分组并在原始数据框中标记
- cytoscape.js - 如何在 cytoscape.js 中实现通过单击节点在两个节点之间添加边的功能?
- jquery - 类型“JQuery”上不存在属性“选项卡”
- javascript - Google Maps JavaScript API 警告:NoApiKeys
- java - android.view.InflateException: Binary XML file line #2: Error inflating class
) - android - 反应原生构建失败