我创建了以下 3 个文件:
base.js
var base = {};
base.one = 1;
base.two = 2;
base.three = 3;
base.bar = function(){
console.log( this.three );
};
a.js
var base = require('./base');
base.three = 6;
module.exports = base;
b.js
var base = require('./base');
module.exports = base;
测试.js
var test_modules = ['a','b'];
test_modules.forEach( function( module_name ){
require( './' + module_name ).bar();
});
然后像这样运行 test.js:
node ./test.js
它输出:
6
6
为什么当我在'a.js'中设置模块'base'的属性'三'时,它会影响'b.js'中的对象?
最佳答案
当您 require()
一个模块时,它会被评估一次并缓存,以便同一模块的后续 require()
不必从磁盘加载,从而获得相同的导出对象。因此,当您更改导出的属性时,对该模块的所有引用都将看到更新后的值。
关于node.js - 同一模块的多个需求似乎会影响每个连续需求的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30769405/