【问题标题】:How can I export static function in ES6?如何在 ES6 中导出静态函数?
【发布时间】:2018-05-03 03:53:40
【问题描述】:

基本代码main.js:

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

export default Something;

其他文件 xxx.js:

import xxx;

// I want to call `ThisIsStaticFunction()` without having to
// write `Something.ThisIsStaticFunction()` how can I achieve this?

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

【问题讨论】:

标签: javascript ecmascript-6 static babeljs


【解决方案1】:

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

export const ThisIsStaticFunction = Something.ThisIsStaticFunction;
export default Something;

import {ThisIsStaticFunction}, Something from 'xxx';

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

export function ThisIsAFunction() {}

export default class Something {
    instanceMethod() {
        const result = ThisIsAFunction();
    }
}

import {ThisIsAFunction}, Something from 'xxx';

const foo = ThisIsAFunction();
const bar = new Something()
const biz = bar.instanceMethod();

【讨论】:

  • 我现在选择你的答案。我关心的是:如果我有这么多静态函数要导出,那么我需要一个一个地分配值,这非常繁琐。
  • 它们是静态函数的原因是什么?你不是在写 Java
  • 我有 OOP 背景,刚刚学习 ReactJS。如果无论如何都不使用,为什么还有static 键?另外,我敢打赌,导出static 和普通函数没有区别。
  • @notalentgeek 导出静态函数与类中的“方法”之间存在巨大的区别。
  • 你能举个例子,告诉我如何导出static函数和普通函数吗?
猜你喜欢
  • 2010-11-04
  • 2021-08-11
  • 2016-04-07
  • 1970-01-01
  • 2017-04-20
  • 2020-06-30
  • 2016-05-11
  • 2020-05-11
  • 1970-01-01
相关资源
最近更新 更多