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 badges
Add a ment  | 

2 Answers 2

Reset to default 12

There 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

本文标签: