I am following a JS tutorial and have come across this example below, and the first one makes sense from what I have learned so far:
function makeCounter() {
function counter() {
return counter.count++;
};
counter.count = 0;
return counter;
}
let counter = makeCounter();
let counter1 = makeCounter();
console.log(counter()); // 0
console.log(counter()); // 1
console.log(counter1()); // 0
So, that makes sense since the new lexical environments are created each time we assign the makeCounter
function to a new variable. What I don't understand is if I am using the property of the function makeCounter
I am still incrementing the makeCounter.count
if I assign it to new variables:
function makeCounter() {
function counter() {
return makeCounter.count++;
};
makeCounter.count = 0;
return counter;
}
let counter = makeCounter();
let counter1 = makeCounter();
console.log(counter()); // 0
console.log(counter()); // 1
console.log(counter1()); // 2