Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/394.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用exports.default函数传递的变量_Javascript_Node.js - Fatal编程技术网

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查看更多信息