I get the basics of the Module Pattern and its use of a closure to allow for private members, BUT I can't quite swallow why the below code does what it does:
var Calculator = function() {
var priv = 0;
return {
changePriv: function() { priv++;},
printPriv: function() { console.log(priv);}
}
}
var myCalc = Calculator();
myCalc.printPriv();
myCalc.changePriv();
myCalc.printPriv();
var myOtherCalc = Calculator();
myCalc.printPriv();
The console output is
0
1
1
So purposefully omitting the new
keyword here, the first call sets myCalc
to a Calculator object. It starts out with a priv
value of 0, has that incremented, and then prints out its new priv
value of 1.
But a) WHY does the next call to Calculator()
end up returning a reference to the SAME object (as evidenced by the second '1')? I know I can use new
here and avoid that, but don't get why I have to. Isn't this function using object literal syntax to essentially create a new object and then return it?
b) Since it does seem to be using the same function stack space (is that even the right way to think of it in JS?), why doesn't it zero out the priv
variable in the process before returning the reference to the same object?
EDIT: Corrected sloppy/stupid mistake (thanks scessor), which DOES now output a new/distinct calculator object even without use of the new
keyword. So that clears up a) and b). My resulting question would have been "Does it matter whether I use new
or not in the invocation of a module-pattern constructor. The answer is, I guess it doesn't matter(?). (Joseph: see http://jsfiddle.net/MvMvy/5/ ...the instanceof operator simply doesn't work with the module pattern either way.)
new
). TheCalculator
function explicitly returns an object so calling it withnew
doesn't make any difference to what it returns. – Suctorial