I have a revealing module pattern.
Let me understand where the variable val
is stored after calling createCounter()
in counter1
and counter2
.
createCounter
creates object including increment()
and getVal()
methods in counter1
and counter2
. If we console.log these two variables we get objects. But where is the val
stored?
Does two different val
exist in corresponding scope of the variables counter1
and counter2
? The concept just does not click in my mind.
Can we anyhow console val
which corresponds to counter1
and counter2
?
function createCounter() {
let val = 0;
return {
increment() { val++ },
getVal() { return val }
}
}
let counter1 = createCounter();
counter1.increment();
console.log(counter1.getVal()); // 1
counter1.increment();
console.log(counter1.getVal()); // 2
let counter2 = createCounter();
console.log(counter2.getVal()) // 0