module.exports = function() 如何调用

joe*_*123 -2 javascript node.js angularjs

快速提问。

如果函数像这样放置,我知道如何导出/导入函数

module.exports = {
    get: get,
    set: set
};
Run Code Online (Sandbox Code Playgroud)

但我不知道如何从另一个文件运行这个函数,我到底需要导入/导出什么?

 module.exports = function() {  
 var this = {};
 var that = {}; .... 
 much more code
 ....
Run Code Online (Sandbox Code Playgroud)

Rid*_*ara 5

假设你有两个文件 A.js 和 B.js

A.js

module.exports = function() {  
   var this = {};
   var that = {}; .... 
   much more code
   ....
}
Run Code Online (Sandbox Code Playgroud)

现在,如果您想在 B.js 中使用它,那么 A.js 正在使用默认导出,并且它正在导出一个函数,因此您可以像这样使用它。

var a = require('./A.js');
// now as A.js is exporing a function so you can call that function by invoking a() function 
// as you have inported it into variable name a
a(); // this will call that
Run Code Online (Sandbox Code Playgroud)

如果你的函数需要这样的参数 module.exports = function(x, y) {

那么你需要可以像这样传递它

a(1, 2);