简体   繁体   English

在 javascript 中导出 object 的深层副本

[英]exporting deep copy of object in javascript

const obj = {A: 2};
module.exports = JSON.parse(JSON.stringify(obj));

Will every module that imports from the above module receive a different copy?从上述模块导入的每个模块都会收到不同的副本吗? Or will they all receive the same copy?还是他们都会收到相同的副本?

Short answer: No. It will return the same instance for every one.简短回答:不。它将为每个实例返回相同的实例。

Long answer:长答案:

I suggest you read about how the module system works in JavaScript/Node.我建议您阅读有关模块系统如何在 JavaScript/Node.js 中工作的信息。

A good mental model is that when a module is imported for the first time and runs all of the code within in order to set the exported variables to what they should be before returning them.一个好的心理 model 是,当一个模块第一次导入并运行其中的所有代码以便在返回它们之前将导出的变量设置为它们应该的值。

The next time it is imported, it will return the exported variables which have already been set.下次导入时,会返回已经设置好的导出变量。 It will not run the module source again for every time you import it.每次导入它时,它不会再次运行模块源。

If you need to have a different object for every import, you will need to generate one by exporting a function instead of a value:如果每次导入都需要不同的 object,则需要通过导出 function 而不是值来生成一个:

const obj = {A: 2};
module.exports = () => JSON.parse(JSON.stringify(obj));

...later ...之后

const uniqueObj = require("./mymodule")(); // call function

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

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