了解Node.js模块:多个需要返回同一个对象吗? [英] Understanding Node.js modules: multiple requires return the same object?

查看:114
本文介绍了了解Node.js模块:多个需要返回同一个对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与有关模块缓存的node.js文档有关的问题:

I have a question related to the node.js documentation on module caching:

模块在第一次加载后被缓存.这表示 (除其他事项外),每个对require('foo')的调用都会得到 返回完全相同的对象(如果它可以解析为相同的对象) 文件.

Modules are cached after the first time they are loaded. This means (among other things) that every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.

多次调用require('foo')可能不会导致模块代码为 执行多次.这是一个重要功能.用它, 可以返回部分完成"的对象,从而允许传递 依赖项即使会导致循环也要加载.

Multiple calls to require('foo') may not cause the module code to be executed multiple times. This is an important feature. With it, "partially done" objects can be returned, thus allowing transitive dependencies to be loaded even when they would cause cycles.

may是什么意思?

我想知道是否require会总是返回相同的对象.因此,如果我需要在app.js中使用模块 A 并在app.js中更改导出对象(需要返回的对象),然后在其中使用模块 B app.js本身需要模块 A ,我是否会总是获得该对象的修改版本或新版本?

I want to know if require will always return the same object. So in case I require a module A in app.js and change the exports object within app.js (the one that require returns) and after that require a module B in app.js that itself requires module A, will I always get the modified version of that object, or a new one?

// app.js

var a = require('./a');
a.b = 2;
console.log(a.b); //2

var b = require('./b');
console.log(b.b); //2

// a.js

exports.a = 1;

// b.js

module.exports = require('./a');

推荐答案

如果app.jsb.js驻留在同一项目中(并且在同一目录中),则它们都将收到A同一实例.从 node.js文档:

If both app.js and b.js reside in the same project (and in the same directory) then both of them will receive the same instance of A. From the node.js documentation:

...每次调用require('foo')都会得到完全相同的对象,如果它可以将解析为相同的文件.

... every call to require('foo') will get exactly the same object returned, if it would resolve to the same file.


a.jsb.jsapp.js不同的npm模块中时,情况有所不同.例如:


The situation is different when a.js, b.js and app.js are in different npm modules. For example:

[APP] --> [A], [B]
[B]   --> [A]

在这种情况下,app.js中的require('a')将解析为与b.js中的require('a')不同的a.js副本,因此返回不同实例.有一个

In that case the require('a') in app.js would resolve to a different copy of a.js than require('a') in b.js and therefore return a different instance of A. There is a blog post describing this behavior in more detail.

这篇关于了解Node.js模块:多个需要返回同一个对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆