JavaScript Module Pattern Variations

Posted Friday 31st August, 2007

The JavaScript Module Pattern is a handy pattern for JavaScript singletons. It allows a developer to scope variables and methods to a given module with both private and public visibility.

Originally proposed by Douglas Crockford (and blogged on the YUI blog by Eric Miraglia), the Module Pattern has recently been through several iterations of pimpage (look Ma – a new buzzword!) at the hands of Christian Heilmann; the first entitled ”Show love to the Module Pattern” and the second, ”Again with the Module Pattern”. Before reading this post, I’d recommend you read all of these articles otherwise this is going to make very little sense!

Having used the pattern quite regularly over the last six months or so, I’d like to add my two-pennies-worth to the discussion with a couple of variations on the theme…

Module Pattern in the Pub

One of Christian’s evolutions of the Module Pattern involves creating an object entitled pub as a private member of the module. This is then returned as public instead of the anonymous object that Douglas first proposed. I’m a big fan of this method because it solves a large number of namespace issues when it comes to dealing with private and public members from within our module. Once again, this is all explained in greater detail in Christian’s post.

The one thing I wasn’t too keen on, when Christian showed me his method, is the fact that we lose a level of indentation – something that Christian actually quotes as a positive feature. I guess this comes down to developer preference but I’ve always liked the fact that that level of indentation allows me to differentiate between the private and public space of the module.

With this in mind, here’s my slight variation on Chris’ original theme:

NEF.FridayDrinks = function () {
  function purchaseBeer() {
  }

  function drink(beer) {
  }

  var pub = {
    sobriety: 10,
    getRoundIn: function(peoplecount) {
      var trayOfDrinks = new Array();
      for (var i = 0; i < peoplecount; i++) {
        trayOfDrinks.push(purchaseBeer());
      }
      return trayOfDrinks;
    },
    getSlyOne: function() {
      drink(purchaseBeer());
    },
    getDrunk: function() {
      do {
        pub.getSlyOne();
        pub.sobriety--;
      } while (pub.sobriety > 0);
    }
  };
  return pub;
}();

var drinks = NEF.FridayDrinks.getRoundIn();
NEF.FridayDrinks.getSlyOne();
NEF.FridayDrinks.getDrunk();

The difference between my method and Christian’s is that, where Chris declares an empty pub object with the object literal and then declares each public method as a property of pub, I declare all public methods within the pub object. It’s a tiny tiny difference, but it brings back that level of indentation we lost without losing any of the added usability of Christian’s method.

Module Pattern Curry

Often, when working with the Module Pattern, you’ll find yourself with only a single public method – usually some form of initialisation script (and, funnily enough, usually called “init”). This is because there isn’t often a need for multiple public methods as most modules are fairly self-contained.

For this reason, I decided to try returning just the method itself; much like I would if I was currying my JavaScript function (although not exactly the same way; for more info check out “Curried Javascript” on svendtofte.com). In this case, we no longer create that public object and, as a result, save a little bit of fuss (and possibly, a little bit of memory too – bonus!), and for all you filesize facists, you’ve knocked out a few lines of code too.

Here’s an example:

NEF.MakeTeaNotLove = function() {
  function getMug() {
    …
  }
  function addTeabag() {
    …
  }
  function addBoilingWater() {
    …
  }
  function addMilk(amount) {
    …
  }
  function addSugar(amount) {
    …
  }
  function stir() {
    …
  }
  return function(milk, sugar) {
    getMug();
    addTeabag();
    addBoilingWater();
    addMilk(milk);
    addSugar(sugar);
    stir();
  };
}();

NEF.MakeTeaNotLove(1, 3);

As you can see, when we call the Module Pattern, rather than having to call an init() member, we can just pass the parameters straight to the returned function. Nice.

Summary

Obviously, one of my examples is only suitable for a particular implementation, and the other simply comes down to developer preference, but hopefully somebody out there will find either one of them useful in some way.

Ultimately, it just goes to show how potentially versatile the JavaScript Module Pattern really is. In a matter of months there have been a number of reworkings, bastardisations, and variations. This is just the sort of thing I love about the JavaScript community – the evolution of code.

Included in: Development, JavaScript, Tutorials, Web

Categories:

  1. Accessibility
  2. Agile
  3. Ajax
  4. Apache
  5. API
  6. Architecture
  7. Books
  8. Browsers
  9. CMS
  10. CouchDB
  11. CSS
  12. Design
  13. Development
  14. Django
  15. Email
  16. Events
  17. Gaming
  18. Grammar
  19. Hardware
  20. HTML
  21. HTTP
  22. Humour
  23. Idea
  24. Information Architecture
  25. JavaScript
  26. jQuery
  27. Lean
  28. Life
  29. Linux
  30. Literature
  31. Mac OS X
  32. Management
  33. Meme
  34. Microformats
  35. Monday
  36. MySQL
  37. Networking
  38. News
  39. Personal
  40. Photoshop
  41. PHP
  42. Process
  43. Python
  44. Reference
  45. REST
  46. Science
  47. SEO
  48. Server
  49. Site
  50. Sitepimp
  51. Social
  52. Spelling
  53. Syndication
  54. Testing
  55. The Future
  56. Thoughts
  57. Tools
  58. Tutorial
  59. Tutorials
  60. Typography
  61. UI
  62. UNIX
  63. Virtualisation
  64. Web
  65. Web Standards
  66. Widgets
  67. Wii
  68. Writing
  69. Xbox
  70. XHTML