There is no detalied explanation of what exactly es6 import and export do under the hood. Someone describe import as an read only view. Check the code below:
// lib/counter.js
export let counter = 1;
export function increment() {
counter++;
}
export function decrement() {
counter--;
}
// src/main.js
import * as counter from '../../counter';
console.log(counter.counter); // 1
counter.increment();
console..log(counter.counter); // 2
My question is if two modules import the same counter module and the first module increment the counter, will the second module also see the the counter as incremented? What under hood do the "import" and "export" do? Under what context is the increment function executing on? What is variable object of the increment function?
// lib/counter.js
export let counter = 1;
export function increment() {
counter++;
}
export function decrement() {
counter--;
}
// src/main1.js
import * as counter from '../../counter';
console.log(counter.counter); // 1
counter.increment();
console..log(counter.counter); // 2
// src/main2.js
import * as counter from '../../counter';
console.log(counter.counter); // what is the result of this, 1 or 2?
It seems to me that the "export" is creating a global object that can be accessed by different modules and it is setting the context of the exported function to that object. If this is the case, the design is wired for me, because modules is not aware of what other modules do. If two modules are importing the same module(counter), one module calls the increment function(example above) which cause the value(counter) changed, the other module does not know that.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…