admin管理员组文章数量:1296884
For example,
If I have 2 modules try1.js and try2.js
try1.js
module.exports.msg = "hello world";
try2.js
try1 = require('./try1');
try1.msg = "changed message";
Does the change in the contents of msg made in try2.js affect try value of msg in try1.js?
For example,
If I have 2 modules try1.js and try2.js
try1.js
module.exports.msg = "hello world";
try2.js
try1 = require('./try1');
try1.msg = "changed message";
Does the change in the contents of msg made in try2.js affect try value of msg in try1.js?
Share asked Jun 10, 2017 at 15:42 Ullas KashyapUllas Kashyap 554 bronze badges2 Answers
Reset to default 12There is no copy at all made. module.exports
is an object and that object is shared directly. If you modify properties on that object, then all who have loaded that module will see those changes.
Does the change in the contents of msg made in try2.js affect try value of msg in try1.js?
Yes, it does. There are no copies. The exports object is shared directly. Any changes you make to that exported object will be seen by all who are using that module.
FYI, a module could use Object.freeze(module.exports)
to prevent changes to that object after the desired properties are added.
Yes, it affects it. Try doing the following. Save this code to a file m1.js:
module.exports.msg = 'hello world';
module.exports.prn = function() {
console.log( module.exports.msg );
}
Then run the node console and try the following:
> const m1 = require('./m1')
undefined
> m1.prn()
xxx
> m1.msg = 'changed'
'changed'
> m1.prn()
changed
本文标签:
版权声明:本文标题:javascript - Does module.exports in node js create a shallow copy or deep copy of the exported objects or functions? - Stack Ove 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741646298a2390202.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论