有人可以帮我理解下面场景中node.js export.* 变量引用的行为吗?
ConfigIndex.js
GLOBAL.app_configs = require('./myconfigs.json');
exports.port = GLOBAL.app_configs.port;
exports.updateConfig = function(newconfigJSONObject, callback)
{
GLOBAL.app_configs = newconfigJSONObject;
callback("update complete");
});
myconfigs.json
{
"port": 443
}
app.js
var config = require('./ConfigIndex.js');
console.log(config.port); //PRINTS the value 443
config.updateConfig ({"port": 9999}, function(resOut) {
console.log(config.port); //PRINTS the value 443 again but I expected 9999
});
--问题--
运行 app.js config.port 时输出 443,但在调用 config.updateConfig 函数后,当我期望值 9999 时,config.port 仍然打印 443。
谁能解释一下吗?
最佳答案
当你这样做时:
exports.port = GLOBAL.app_configs.port;
因为 .port
只是一个数字,所以 exports.port
仅包含该数字的副本。它不再以任何方式与 GLOBAL.app_configs.port 建立任何连接,因此无论您将 GLOBAL.app_configs.port 更改为什么,它对完全独立的变量exports.port
。
也许这可能会让它变得更加明显:
var x = 3; // assign primitive value 3 to x
var y = x; // copy the primitive value 3 from x to y
x = 4; // assign primitive value 4 to x
console.log(x); // shows 4
console.log(y); // shows 3
在 Javascript 中,像数字这样的原始值是在赋值时按值分配的,并成为单独的值(您可以将其想象为将值复制到新变量中)。
<小时/>Javascript 中的对象是通过指针分配的,这可能会让您认为它可能具有您期望的行为,但对于像数字这样的基元来说则不然。
因此,让值以您显示的方式更改的唯一方法是将属性嵌入到对象中,并在变量中保留对该对象的引用。然后,当有人更改该对象中的属性并且您引用该属性时,您将看到更改后的值。
关于javascript - node.js - 了解变量引用的导出行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32365722/