同一模块的多个要求似乎会影响每个连续要求的范围

Multiple requires of same module seem to affect scope of each successive require

我创建了以下 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;

test.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'的属性 'three',却影响了'b.js'中的对象?

当您 require() 一个模块时,它会被评估 一次 并被缓存,这样同一模块的后续 require() 就不必加载从磁盘中获取相同的导出对象。因此,当您更改导出的属性时,对该模块的所有引用都将看到更新后的值。

您正在为 base 模块引入 global 状态。

模块 a 变异了 base 然后也将其导出,这意味着对 base 的任何进一步引用都将具有更新的值。

最好用test.js

中的以下脚本来演示
var testModules = ['b', 'a'];
testModules.forEach(function(module) {
  require('./' + module).bar();
});

现在当你 运行 node test.js 时,你会看到

3
6

为什么?

因为模块的包含顺序发生了变化。

我该如何解决?

简单,去掉全局状态。一种选择是像这样使用原型

var Base = function() {
  this.one = 1;
  this.two = 2;
  this.three = 3;
};
Base.prototype.bar = function() {
  console.log(this.three);
};
module.exports = Base;

然后,里面a.js

var Base = require('./base');
var baseInstance = new Base();
baseInstance.three = 6;
module.exports = baseInstance;

里面 b.js

var Base = require('./base');
module.exports = new Base();

现在当你 运行 你原来的 test.js 时,输出应该是

6
3