/ JavaScript

Mastering the Module Pattern

I’m a massive fan of JavaScript’s Module Pattern and I’d like to share some use cases and differences in the pattern, and why they’re important. The Module Pattern is what we’d call a “design pattern”, and it’s extremely useful for a vast amount of reasons. My main attraction to the Module Pattern (and it’s variant, the Revealing Module Pattern) are because it makes scoping a breeze, and doesn’t overcomplicate JavaScript design.

It also keeps things very simple and easy to read and use, uses Objects in a very nice way, and doesn’t bloat your code with repetitive this and prototype declarations. I thought I’d share some insight as to the awesome parts of the Module, and how you can master it and its variants and features.

Creating a Module

To understand what a Module can give you, you’ll need to understand what the following function concept does:

(function () {
  // code

It declares a function, which then calls itself immediately. These are also known as Immediately-Invoked-Function-Expressions’s, in which the function creates new scope and creates “privacy”. JavaScript doesn’t have privacy, but creating new scope emulates this when we wrap all our function logic inside them. The idea then is to return only the parts we need, leaving the other code out of the global scope.

After creating new scope, we need to namespace our code so that we can access any methods we return. Let’s create a namespace for our anonymous Module.

var Module = (function () {
  // code

We then have Module declared in the global scope, which means we can call it wherever we like, and even pass it into another Module.


Read more @ Todd Motto