首页 > 解决方案 > 如何将一个.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

标签: javascriptclassasynchronousimport

解决方案


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();


推荐阅读