The following function returns an object. It's taken from a MDN document. This object that is returned has properties that are functions, which reference the "private" function changeBy().
I'm pretty sure that the only way an increment() call will resolve the changeBy() function call is to have access to the scope chain - the scope of the enclosing/parent function.
Q: Is the scope chain property set on the increment() function where it is declared, even though it is declared inside an object, and has not been invoked at that point?
Note I'm being pointed to How do JavaScript closures work? as a possible duplicate.
The magic is that in JavaScript a function reference also has a secret reference to the closure it was created in — similar to how delegates are a method pointer plus a secret reference to an object
Q: The secret bit is what I'm asking about, which is not explained in the answer given in there. Where is this reference stored?
var makeCounter = function() {
var privateCounter = 0;
function changeBy(val) {
privateCounter += val;
}
return {
increment: function() {
changeBy(1);
},
value: function() {
return privateCounter;
}
}
};
var counter1 = makeCounter();
alert(counter1.value()); /* Alerts 0 */
counter1.increment();
alert(counter1.value()); /* Alerts 1 */