I am bit confused by the following JavaScript code:
// Because this function returns another function that has access to the
// "private" var i, the returned function is, effectively, "privileged."
function makeCounter() {
// `i` is only accessible inside `makeCounter`.
var i = 0;
return function() {
console.log( i++ );
};
}
// Note that `counter` and `counter2` each have their own scoped `i`.
var counter = makeCounter();
counter(); // logs: 1
counter(); // logs: 2
var counter2 = makeCounter();
counter2(); // logs: 1
counter2(); // logs: 2
i; // ReferenceError: i is not defined (it only exists inside makeCounter)
I don't understand how come the i variable in counter and counter2 aren't referring to the same i value?
My understanding is that counter and counter2 should reference the same function since both have been assigned the same function and a function is a "reference datatype" and shouldn't create a separate copy.
Also, how is it possible the counter and counter2 access the "private" value set in makecounter function?