简体   繁体   English

在Node.js中,为什么使用require函数的模块之间的变量相等?

[英]In Node.js, why are variables equal the same across modules using the require function?

I have the following files in the same directory: 我在同一目录中有以下文件:

data.js

var anArray = [1,2];
module.exports = anArray;

mod1.js

var data = require('./data');
module.exports = data;

mod2.js

var data = require('./data');
module.exports = data;

main.js

var mod1 = require('./mod1');
var mod2 = require('./mod2');

When I do mod1 === mod2 it is true Why is that? 当我做mod1 === mod2这是true吗? My initial belief was that mod1 and mod2 files should contain an array but that are different (different references to the array objects). 我最初的想法是mod1和mod2文件应该包含一个数组,但是它们是不同的(对数组对象的不同引用)。

This is because modules are cached. 这是因为模块被缓存。 Since you're referencing the same module twice, the second one is returning the exact same as the first. 由于您两次引用相同的模块,因此第二个模块返回与第一个模块完全相同的模块。 In your example, it's the same as doing the following: 在您的示例中,它与执行以下操作相同:

const arr1 = [1,2]
const arr2 = [1,2]

arr1 === arr1 // true
arr1 === arr2 // false

The last line is false because you're comparing two different arrays. 最后一行是false因为您正在比较两个不同的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM