Javascript Module Pattern

Dictionary.com defines ‘module’ as a self contained unit or item. In programming I like to think of modules as independent pieces of code that can be used to construct a more complex structure. The module pattern in JavaScript is essentially a way to modulize JS code in an application.

This is an example of the module pattern:

var Module = function() {
  var privateProperty = 'foo';

  function privateMethod() {
    // do something
  };  

  return {
    publicProperty: "",
    publicMethod: function(args) {
      // do something
    },
    privilegedMethod: function(args){
      privateMethod(args);
    }
  };
}

The code above is an overview of the module pattern. Its aim is to provide an interface to interact with data. There are a private method and a private property. It returns an object that has a public property, a public method, and a privileged method that have access to the private method within the module. Public properties and methods are accessed by simply calling that property on the object, e.g obj.publicProperty. Private methods, on the other hand, are not; e.g obj.private_method // undefined.This limits what the application can do with the data.

var cellPhone = function() {
  var batteryLevel = 100;

  function useBattery(energyConsumed) {
    if(batteryLevel - energyConsumed < 0) {
      console.log('Out of battery');
    }else{
      batteryLevel -= energyConsumed;
    }
  };  

  return {
    cellPhoneOwner: "Basia",
    changeCellPhoneOwner: function(owner) {
      this.cellPhoneOwner = owner;
    },
    turnedOn: function(energyUsed){
      useBattery(energyUsed);
    }
  };
}

var samsung = cellphone();

samsung.turnedOn(80); // undefined

samsung.turnedOn(30) // 'Out of battery'

Above is the example of a cellPhone function or in this case a constructor. It creates a cellphone object where users are able to change the property phoneOwner, but not batteryLevel. This is probably the most tedious cell phone as it keeps going on until it runs out of battery.

In this function we are limiting the user changing the battery level by having the privileged methodturnedOn call the private function useBattery. useBattery in its turn has access to the private variable batteryLevel. batteryLevel cannot be changed directly on cellPhone.

The last lines of the code above creates a variable samsung and applies it to the constructor function cellPhone. When samsung is turnedOn, it is given a value for energyUsed. If the energy used is more than the batteryLevel the console prints 'Out of battery'

The idea of the module pattern is to limit access to certain parts of the api. Think of a car, it makes sense to give access to public properties to users such as wheel, radio, etc, but not parts related to the engine. If the user are given access to the engine private parts and they did not know what they are doing, it might be dangerous messing around it and it will break as a result.

To sum up, modules are organized pieces of code. They act as independent units that can be used and reused as part of a complex structure such as an application programming interface. Overall, they are great because it prevents access to data that are not essential for users to know when using the program(think of engine in a car object) or dangerous for users to fiddle with(think of credit card number). In Javascript, the module pattern is a way to design modules. Its objective is to limit access to private variables by having it only be accessible via private methods. The module pattern relies heavily on Javascript closures, but this is a topic for another blog post.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s