Javascript 全局变量还是在Node.js中通过引用调用?
在Node.js中,我有如下代码:Javascript 全局变量还是在Node.js中通过引用调用?,javascript,node.js,Javascript,Node.js,在Node.js中,我有如下代码: //file main.js var otherfile = require('other.js'); var myname = 'aaa'; otherfile.setname(); 现在,我想更改myname变量,而不将此变量作为参数发送 //file other.js module.exports = { setname: function(){ myname = 'bbb'; } } 我能做这个吗?我必须使用电话咨询
//file main.js
var otherfile = require('other.js');
var myname = 'aaa';
otherfile.setname();
现在,我想更改myname
变量,而不将此变量作为参数发送
//file other.js
module.exports = {
setname: function(){
myname = 'bbb';
}
}
我能做这个吗?我必须使用电话咨询吗?或者使用全局变量?即使将此变量作为参数传递,您也无法更改此变量,因为您只能按值传递
'aaa'
字符串,而不是实际变量的绑定。您无法从其他文件访问此变量,因为它将超出范围
您可以做的是传递一个闭包,该闭包的作用域中包含此变量:
//file main.js
var otherfile = require('./other.js');
var myname = 'aaa';
function changeValue(value) {
myname = value;
}
console.log(myname);
otherfile.setname(changeValue);
console.log(myname);
//file other.js
module.exports = {
setname: function (fn) {
fn('bbb');
}
}
你有帮助吗?如果是这样,那么你可以让其他人在搜索时看到你的问题得到了回答。请解释你为什么要这样做。如前所述,不清楚为什么会有人想这样做。