I'm learning about CommonJS from this blog and having trouble understanind the below in regards to the code:
In this example, we basically make two copies of the module: one when we export it, and one when we require it. Moreover, the copy in main.js is now disconnected from the original module. That’s why even when we increment our counter it still returns 1 — because the counter variable that we imported is a disconnected copy of the counter variable from the module.
// lib/counter.js
var counter = 1;
function increment() {
counter++;
}
function decrement() {
counter--;
}
module.exports = {
counter: counter,
increment: increment,
decrement: decrement
};
// src/main.js
var counter = require('../../lib/counter');
counter.increment();
console.log(counter.counter); // 1
So if 2 copies are created, then wouldn't each copy have their own version of counter
and increment
? Thus each one would be connected to their own function of increment
? The author is saying that there is 1 copy of counter
, increment
, and decrement
that is in module.exports and another copy in the var counter = require('../../lib/counter')
so shouldn't the counter.increment
calling the increment
function in the require copy and the console.log(counter.counter)
return the connected counter in the require copy?