Javascript 如何使用exports.default函数传递的变量
我想找到访问函数变量的最佳方法,这些变量在另一个模块的其他函数中用作参数。Javascript 如何使用exports.default函数传递的变量,javascript,node.js,Javascript,Node.js,我想找到访问函数变量的最佳方法,这些变量在另一个模块的其他函数中用作参数。parsefile.js是一个Node.js脚本,作为包模块和两个函数导出getfirst和getsecond需要从parsefile('a','b','c')访问从index.js传递的变量,如'a','b'。除了使用global,我们还有其他方法吗 // index.js from some application const parsefile = require('./parsefile') parsefile('
parsefile.js
是一个Node.js脚本,作为包模块和两个函数导出getfirst
和getsecond
需要从parsefile('a','b','c')
访问从index.js传递的变量,如'a','b'
。除了使用global
,我们还有其他方法吗
// index.js from some application
const parsefile = require('./parsefile')
parsefile('a', 'b', 'c')
//parsefile.js exports about package module
function getfirst() {
if (global.f && global.s) {
return `i have totally 2 arguments: ${global.f}///${global.s}`
}
return `first arguments is ${global.f}`
}
function getsecond() {
return `second arguments is ${global.s}`
}
module.exports = (...args) => {
global.f = args[0];
global.s = args[1];
Promise.all([getfirst(), getsecond()]).then(([first, second]) => {
console.log(`return from getfirst: ${first}`);
console.log(`return from getsecond: ${second}`);
});
}
不,不要使用全局变量!只需将
parsefile
函数通过参数获得的参数传递给正在调用的函数:
function getfirst(f, s) {
if (f && s) {
return `i have totally 2 arguments: ${f}///${s}`;
}
return `first arguments is ${global.f}`;
}
function getsecond(s) {
return `second arguments is ${s}`
}
module.exports = (f, s) => {
Promise.all([
getfirst(f, s),
getsecond(s)
]).then(([first, second]) => {
console.log(`return from getfirst: ${first}`);
console.log(`return from getsecond: ${second}`);
});
};
不使用global的原因是什么?@jacobcan118查看更多信息