I'm working on implementing the Javascript module pattern, and I understand how to use it pretty well. What I don't understand is the concept of what happens to the private variables and methods once the function has run and the return value been assigned.
If I have a module like so:
var myModule = (function() {
var privateVar1, privateVar2 = 10, privateLogger, privateHello;
privateLogger = function(someInput) {
console.log(someInput);
};
privateHello = function() { console.log('Hello World!');}
return {
publicVar: 'myName',
publicCounter: 0,
publicIncrementor: function(bar) {
bar++;
privateLogger(bar);
privateHello();
}
}
})();
console.log(myModule);
console.log(myModule.publicIncrementor.toString());
When I run the file, I then get an output of:
{ publicVar: 'myName',
publicCounter: 0,
publicIncrementor: [Function] }
function (bar) {
bar++;
privateLogger(bar);
privateHello();
}
From this, it seems like myModule is now a variable that only knows what publicVar, publicCounter and publicIncrementor are. So how does it know what privateHello is? Where does that function definition exist after instantiation? It's not a part of myModule (the console.log(myModule) doesn't show it). It's not a global function (avoiding that is the point of this pattern). So where does that function definition live now?
Or is it that the privateHello function gets re-defined every time I call myModule.publicIncrementor?