NodeJS,创build一个函数,然后导出它

如何创build一个只在mymodule.js中使用的函数

但也可以从mymodule.js之外访问

当然我也可以这样做:

module.exports = { myfunction: function() { return "HELLO"; }, 

};

但是,有没有办法一次声明一个函数并稍后导出?

mymodule.js:

 var x = function P(inp) { console.log('P'); } module.exports = { method: x(), } 

other.js:

 var mac = require('./mymodule.js'); mac.x(); //<-- does not work 

在mymodule.js中:

 function P(inp) { // you may or may not declare it with "var x ="..both are valid console.log('P'); } module.exports = { method: P // "method" is the name by which you can access the function P from outside }; 

在other.js中:

 var mac = require('./mymodule.js'); mac.method(); // Call it by the name "method" 

如果你想要,你也可以保持相同的名字。 即,在mymodule.js中:

 module.exports = { P: P // In this case, "P" is the name by which you can access the function P from outside }; 

你也可以像这样导出它:

 exports.P = P; // This has the same effect as above example 

要么:

 module.exports.P = P; // This has the same effect as above example 

但是,如果您只想从mymodule.js中导出一个函数,那么您可以执行@ LucaArgenzianobuild议的操作,如下所示:

在mymodule.js中:

 function P(inp) { console.log('P'); } module.exports = P; 

在其他.js

 var mac = require('./mymodule.js'); mac();