如何在ES6中导出静态功能?

not*_*eek 3 javascript static ecmascript-6 babeljs

基本代码main.js:

class Something {
  static ThisIsStaticFunction () { ... }
}

export default Something;
Run Code Online (Sandbox Code Playgroud)

其他文件xxx.js:

import xxx;

// I want to call `ThisIsStaticFunction()` without having to
// write `Something.ThisIsStaticFunction()` how can I achieve this?
Run Code Online (Sandbox Code Playgroud)

我想打电话ThisIsStaticFunction()而不必写Something.ThisIsStaticFunction()我怎样才能做到这一点?

Bry*_*hen 5

您可以将静态函数别名为普通函数

export const ThisIsStaticFunction = Something.ThisIsStaticFunction;
export default Something;
Run Code Online (Sandbox Code Playgroud)
import {ThisIsStaticFunction}, Something from 'xxx';
Run Code Online (Sandbox Code Playgroud)

通常在Javascript(与Java不同)中,您可以使用普通函数而不是静态函数.

export function ThisIsAFunction() {}

export default class Something {
    instanceMethod() {
        const result = ThisIsAFunction();
    }
}
Run Code Online (Sandbox Code Playgroud)
import {ThisIsAFunction}, Something from 'xxx';

const foo = ThisIsAFunction();
const bar = new Something()
const biz = bar.instanceMethod();
Run Code Online (Sandbox Code Playgroud)

  • 他们成为静态功能的原因是什么?你不是在写Java (2认同)