I'm understanding the principle of module pattern but when I look at the different definition I struggle to understand how anonymous functions work. In particular, takes those three examples
Example 1, (from http://viralpatel.net/blogs/javascript-module-pattern/)
CalcModule = (function(){
var pub = {};
pub.add = function(a, b) {
console.log('in add()', a, b);
return a + b;
};
pub.sub = function(a, b) {
console.log('in sub()', a, b);
return a - b;
};
return pub;
})();
which is used as
CalcModule.add(5,2) //returns : 7
Example 2 (from Learning JavaScript Design Patterns 1.5.2, Addy Osmani)
var testModule = (function () {
var counter = 0;
return {
incrementCounter: function () {
return counter++;
},
resetCounter: function () {
console.log( "counter value prior to reset: " + counter );
counter = 0;
}
};
})();
which is used as
testModule.incrementCounter()
Example 3 (from http://css-tricks.com/how-do-you-structure-javascript-the-module-pattern-edition/)
var s,
NewsWidget = {
settings: {
numArticles: 5,
articleList: $("#article-list"),
moreButton: $("#more-button")
},
init: function() {
// kick things off
s = this.settings;
}
};
which, by the way, I don't know ho to use it.
As you see, the methods, for example add, incrementCounter and init are defined in different ways:
- Example 1: by means of a private variable pub
- Example 2: in the return method!
- Example 3: as method of the constructor NewsWidget
Question: In my mind Example 3 is what I would do and I don't understand why Example 1 and 2 are not used in the following way
- Example 1: CalcModule.pub.add(5,2)
- Example 2: no idea