Module pattern in Javascript for dummies

I find the module pattern in Javascript very interesting, because of its scope feature (anonymous closure), extendibility (with global imports) and clean code style. If you are not familiar with this, keep going reading.

Module Pattern in Javascript

Let’s go with a simple example

var BotModule = (function () {
 
  var model = "BOT14A88";
  var name  = null;
  var hasName = function () {
    return name && name.length > 0;
  };
  var hi = function() {
    return "Greetings, human";
  };
 
  return {
    model,
    // You can't change name prop, instead you should use setName()
    setName: function (humanName) {
      this.name = humanName;
    },
    hi: hi,
    // You can also define it inline
    goodbye: function () {
      // You can use private properties or functions
      return "See you"+ ( hasName() ? ', '+this.name : '' );
    },
    // As an object, you can define any properties and functions
    // In this case, hola() is an alias for hi()
    hola: hi
  };
 
})();

Keynotes:

  • Whatever you return in the ouput object, it will be public.
  • Whatever else, it will be private.
  • The module is wrapped into a Immediately-Invoked-Function-Expressions, in which the function creates a new scope and a kind of privacy.

If you need one more example, I used it sometime ago in mileagifyJS with the Route module and Map module modules.

Bonus

You find out you have to put the module’s full code into a single file. That’s right but you can extend it 🙂

// After the previous code, you can extend it
var Bot2Module = (function (BotModule) {
 
  BotModule.model = "BOT14A88-2";
 
  BotModule.awesomeNewFeature = function() {
    return "I know I'm $100 more expensive but now I have 2 more LEDs";
  }
 
  return BotModule;
 
})(BotModule);

Further reading

  1. Wikipedia
  2. Javascript Design Pattern book

David Burgos

Read more posts by this author.