javascript - 如何将一个.js文件中的类导入另一个
问题描述
我试图了解如何将 .js 文件中的类导入到另一个文件中,以便我可以在导入的类中运行异步函数。
//file called helloworld.js
class helloworld {
async greetings(){
console.log("hello world")
}
}
export default helloworld;
我正在尝试在下面的代码中使用名为 greetings 的异步函数
import helloworld from './helloworld';
console.log(helloworld.greetings)
我运行时会导致错误
节点 helloworld_import.js
解决方案
1. helloworld
是一个类,所以你需要先实例化。那么只有你可以使用它的methods
.
2. greetings
不是属性,它是一个对象,所以需要调用/调用/执行它()
。
import helloworld from "./helloworld";
const obj = new helloworld();
obj.greetings();
如果您想使用类名访问helloworld
,请将函数设为greetings
静态(为简单起见,我在单个 js 文件中使用过,如果需要,可以根据需要导入和导出)
class helloworld {
static async greetings() {
console.log("hello world");
}
}
helloworld.greetings();
推荐阅读
- python - Python - 池不使用所有核心
- pca - 预处理.StandardScaler()。处理字符串特征?
- javascript - 如何将值从 HTML 传递到 JavaScript?
- python - 如何在系统日志消息中设置主机头字段?
- react-native - 如何更改键盘上的“返回”按钮?
- android - 尝试在空对象引用上调用虚拟方法“void com.google.android.gms.ads.AdView.loadAd(com.google.android.gms.ads.AdRequest)”
- node.js - mongoDB nodejs驱动程序中的唯一键
- delphi - {$SetPEFlags IMAGE_FILE_LARGE_ADDRESS_AWARE} 无法在我的应用程序中工作
- javascript - CSS 定位 2 个 div - 滚动到较短的一个的末尾
- ssl - grpc中不安全的连接是什么意思?