I have a few questions about using the Module Pattern for JavaScript programming. I have seen guides on the pattern that utilize it in 2 different ways. The first is like this:
This method is from CSS Tricks, Module Pattern
var s,
NewsWidget = {
settings: {
numArticles: 5,
articleList: $("#article-list"),
moreButton: $("#more-button")
},
init: function() {
// kick things off
s = this.settings;
}
};
The second method, I will use the same code but in a different way.
var s,
NewsWidget = (function(){
// Any variables or functions in here are private
var privateVar;
// All variables or functions in returned object become public
return {
settings: {
numArticles: 5,
articleList: $("#article-list"),
moreButton: $("#more-button")
},
init: function() {
// kick things off
s = this.settings;
}
}
}());
Now looking at these two examples, my assumption would be to only use the latter method because of the ability to use private variables due to closures..? Am I correct? The first method does not use a closure and therefore is in the global memory scope and cannot have private members. Why is it then, that CSS Tricks and other people use the first method as an example when it does not seem to have any real purpose?
Secondly, I am curious how the Module Pattern handles multiple objects of the same type? Unlike the Factory Pattern which is used to get any number of JavaScript Objects, the Module Pattern just executes the anonymous function once, therefore if I have a Module called BlogPost that defines all the attributes of a blog post, then how can I create multiple instances of this object?