Reputation: 33
I have an object obj1 declared in a file, lets say A.js. I export the object obj1 and copy a local object, say obj2 to another file, say B.js Now, if I export obj1 in a 3rd file, say C.js, I should have the values of obj2 stored in it. But it seems that obj1 is holding the values that it had in A.js
**A.js**
export const obj1 = {};
**B.js**
import obj1 from "A";
//called from main loop
someFunction()
{
Object.assign(obj1,obj2);
//At this point, the obj1 is holding the value of obj2
}
**C.js**
import obj1 from "A";
//obj1 is not holding the value of obj2 any more.
Upvotes: 0
Views: 102
Reputation: 9873
First of all, there's no strict guarantee of import order in Node.JS. Sometimes B.js
loads before C.js
, and sometimes – the opposite. But even if you know for sure the import order, that's not something you should rely on, because it might change in the future.
Second, imports are most likely cached, so by the time you get to the second import
, it actually imports whatever was imported the first time, – which was the unchanged value.
Most commonly, exported objects are designed to be immutable. You could implement this approach in the following way:
// defaults.js
export const defaults = { foo: 'foo1', bar: 'bar1' };
// merge.js
import { defaults } from './defaults';
export const merge = (overrides) => ({ ...defaults, ...overrides });
// The `defaults` is not mutated
import { merge } from './merge';
const result = merge({ foo: 'foo2', baz: 'baz2' });
// { foo: 'foo2', bar: 'bar1', baz: 'baz2' }
Upvotes: 1