【问题标题】:Javascript export/import class [duplicate]Javascript导出/导入类[重复]
【发布时间】:2018-03-03 13:35:39
【问题描述】:

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

TypeError: _base2.default.test 不是函数

(正在使用 Babel 进行编译)

file1.js

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

file2.js

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

【问题讨论】:

    标签: javascript import ecmascript-6 export babeljs


    【解决方案1】:

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

    试试

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

    【讨论】:

      【解决方案2】:

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

      您可以将 file2.js 更改为,

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

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

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

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

      【讨论】:

        猜你喜欢
        • 2020-07-05
        • 2019-01-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-20
        • 2021-03-28
        • 2020-09-21
        相关资源
        最近更新 更多