0

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?

Matt Hintzke
  • 7,744
  • 16
  • 55
  • 113
  • to manage multiple instance => var myFirstInstance = new NewsWidget();var mySecondInstance = new NewsWidget(); – ale Jun 10 '14 at 17:09
  • Oh so it can be treated just like a Constructor Pattern object? I thought that `typeof NewWidget === "object"`, not a function? – Matt Hintzke Jun 10 '14 at 17:11
  • in the second case NewsWidget is a function for sure – ale Jun 10 '14 at 17:11
  • Even though the anonymous function returns an Object? – Matt Hintzke Jun 10 '14 at 17:14
  • mmh nice shoot, maybe I'm in a trouble with scope? :) – ale Jun 10 '14 at 17:14
  • If I were to remove the parenthesis that wrap that anonymous function then I believe you would be correct. – Matt Hintzke Jun 10 '14 at 17:16
  • possible duplicate of [JavaScript module pattern with example](http://stackoverflow.com/questions/17776940/javascript-module-pattern-with-example) – ale Jun 10 '14 at 18:45
  • @Infer-On: I don't think it's a dupe, the questions the OP asked are quite different even if they are dealing with the same subject. – Bergi Jun 10 '14 at 19:04

2 Answers2

1

my assumption would be to only use the latter method because of the ability to use private variables due to closures..? Am I correct?

Yes. If you need private variables.

The first method does not use a closure and therefore is in the global memory scope and cannot have private members.

Notice however that even in the second example, the s variable is unnecessarily global.

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?

For simplicity. Either when you don't have local variables around (because you don't need them, or you did model private things as properties), or when the author just doesn't care. Or didn't bother to write down the implicit IEFE.

Secondly, I am curious how the Module Pattern handles multiple objects of the same type?

It does not. Modules are singletons. They can have constructors or factories as fields, though, when you need to instantiate module-related objects. Still, there is only ever one (global) module object.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

Your first example is not a Module Pattern, its a simple Object Literal initializer. Only the second example are a Module Pattern, first example doesn't give the possibility to define encapsulation of private member or function

Quoted from Learning JavaScript Design Patterns, this is the typical pattern(there is some variation):

In JavaScript, the Module pattern is used to further emulate the concept of classes in such a way that we're able to include both public/private methods and variables inside a single object, thus shielding particular parts from the global scope. What this results in is a reduction in the likelihood of our function names conflicting with other functions defined in additional scripts on the page.

var myNamespace = (function () {

  var myPrivateVar, myPrivateMethod;

  // A private counter variable
  myPrivateVar = 0;

  // A private function which logs any arguments
  myPrivateMethod = function( foo ) {
      console.log( foo );
  };

  return {

    // A public variable
    myPublicVar: "foo",

    // A public function utilizing privates
    myPublicFunction: function( bar ) {

      // Increment our private counter
      myPrivateVar++;

      // Call our private method using bar
      myPrivateMethod( bar );

    }
  };

})();
ale
  • 10,012
  • 5
  • 40
  • 49
  • So the basically the guy at CSS Tricks is just throwing BS around and calling it module pattern? – Matt Hintzke Jun 10 '14 at 17:27
  • eh, I'd like to say no – ale Jun 10 '14 at 17:29
  • I've been reading the same book, which is what brought me to this question because I saw the CSS Tricks example just before and it confused me – Matt Hintzke Jun 10 '14 at 17:33
  • @MattHintzke Found it! http://stackoverflow.com/questions/17776940/javascript-module-pattern-with-example possible duplicate? – ale Jun 10 '14 at 17:41
  • Thanks, any idea about my second question though? I still don't see a way of instantiating multiple objects of the same Module design? – Matt Hintzke Jun 10 '14 at 17:43
  • You are right, because there is also a singleton without a private instance http://stackoverflow.com/questions/13429169/different-between-module-pattern-and-singleton-pattern – ale Jun 10 '14 at 17:45
  • Yes and No. Even plain object literals can be (and are) considered to be modules, see http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript. The term *module pattern* can both refer to "modularisation" as the structural design pattern, and to the object-returning-IEFE creational pattern for encapsulation. – Bergi Jun 10 '14 at 19:10