如何创建仅在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
答案 0 :(得分:2)
在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导出一个函数,那么您可以执行@ LucaArgenziano建议的操作,如下所示:
在mymodule.js中:
function P(inp) {
console.log('P');
}
module.exports = P;
在other.js
var mac = require('./mymodule.js');
mac();