Javascript 导出/导入类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46356810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:24:55  来源:igfitidea点击:

Javascript export/import class

javascriptimportecmascript-6exportbabeljs

提问by Alan P.

Why is this example below not outputting "hello world"? Instead, I am getting:

为什么下面这个例子不输出“hello world”?相反,我得到:

TypeError: _base2.default.test is not a function

类型错误:_base2.default.test 不是函数

(it is being transpiled with Babel)

(它正在用 Babel 转译)

file1.js

文件1.js

import Example from './file2';
console.log(Example.test());

file2.js

文件2.js

export default class Example {
  test() {
    console.log('hello world');
  }
}

回答by James Maa

You are only importing the class, but not making an instance of the class

您只是导入类,而不是创建类的实例

Try

尝试

var myInstance = new Example()
myInstance.test()

回答by prabushitha

If you want to call a method as a class method (without creating an object instance) you can try static methods.

如果您想将方法作为类方法调用(不创建对象实例),您可以尝试静态方法。

You can change the file2.jsas,

您可以将file2.js更改为,

export default class Example {
  static test() {
    console.log('hello world');
  }
}

then call it by using the class name in file1.jsas

然后使用file1.js 中的类名调用它作为

import Example from './file2';
console.log(Example.test());

Refer James Maaanswer if you want to call it as an instance method.

如果您想将其作为实例方法调用,请参考James Maa 的回答。