声明导出时调用函数的目的(以及任何其他影响)是什么?

时间:2019-01-17 17:16:34

标签: javascript ecmascript-6 import module export

简单导出以函数/变量/类声明结尾,例如 export default hello

假设hellohello模块中的函数。在导出的模块中调用export default hello()和在导入hello()的模块中调用import hello from "./hello"有什么区别?

似乎没有什么区别,除了第二个选项需要在导入hello的模块中初始化(调用)函数。

// hello.js

function hello () {
  console.log("hello")
 }

// 1st option function declaration
export default hello

// 2nd option - run function on export
export default hello()

// index.js

import hello from "./hello";

// 1st option initialise (calling)
hello();

// 2nd option - no calling needed

在整个网络中进行了搜索,但找不到可能的副作用,或者其中哪些是处理包含和导出功能的模块的更好方法。

1 个答案:

答案 0 :(得分:0)

如果从两个不同的模块导入函数,则:

  // A
 import hello from "./hello";
 hello();

 //B
 import hello from "./hello";
 hello();

该函数被调用两次。如果导出函数结果,则该函数肯定只会运行一次。

这表示在第二种情况下完全没有功能是没有意义的,

 function hello () {
  console.log("hello");
  return "something";
 }

 export default hello();

等于:

 console.log("hello");
 export default "something";