来自nodejs的示例代码:
来自JS1.js的代码:
var js2=require("../../util");
var dataName="Billy";
function hello1(){
js2.hello2("message");
}
来自JS3.js的代码:
var js2=require("../../util");
var dataName="Tom";
function hello3(){
js2.hello2("message");
}
来自JS2.js的代码:
exports.hello2=hello2;
function hello2(arg1){
console.log(arg1);
//Here I need the data in global variable "dataName" of file JS1.js or JS3.js
}
我需要访问调用者js文件的全局变量。
答案 0 :(得分:1)
所有模块在node.js中共享一个global
对象。所以在JS1.js ......
global.dataName = "Billy";
...然后在JS2.js中:
console.log(global.dataName);
但是,以这种方式使用global
通常被视为不良形式也就不足为奇了。除非你有一个特殊的理由不希望JS2依赖JS1,否则最好只让JS2导出dataName
作为module.exports
的一部分。