It seems like you need to understand how return
works in functions in order to understand why the provided examples behave the way they do.
Example 1: You create a new variable pub
and adding two methods to it: add
and sub
. At the end, you're returning the pub variable to CalcModule
So when you call CalcModule
, it returns the following object with two methods:
CalcModule = {
add: function() {...},
sub: function() {...}
}
Example 2: Let's rewrite example 2 similar to example 1...
var testModule = (function () {
var counter = 0;
var pub;
pub.incrementCounter: function () {
return counter++;
}
pub.resetCounter: function () {
console.log( "counter value prior to reset: " + counter );
counter = 0;
}
return pub;
})();
We know pub
is an object...
pub = {
incrementCounter: function() { ... },
resetCounter: function() { ... }
}
and we're returning pub
to testModule
... therefore...
testModule = {
incrementCounter: function() {...},
resetCounter: function() {...}
}
Hope this is helpful.