Module Pattern in JavaScript

In JavaScript, code encapsulation can be achieved using Modules Patterns. In addition, it is used to create private and public properties. There are various ways a module pattern can be implemented. In this article, we will learn to create a module pattern in ES5. Before we go ahead and start looking into implementation of the module pattern, here are some of the benefits:

  • Freeze the scoping
  • Code encapsulation
  • Creating private or public scope
  • Creating a namespace
  • Creating public and private encapsulation

We can implement a module pattern using JavaScript Object Literals and Immediately- Invoked function expression. Just to refresh your memory, an object literal will look like the below listing:

You can add properties after creation of object. Also, an Immediately- Invoked function expression looks like the example below:

With combination of these two, we can implement Module Patterns in JavaScript. Let us start with creating the module:

It is a self-contained module or an anonymous closure. It creates the scope for the function and everything is wrapped inside that function itself. So, when we tried to access price outside the function, it was undefined. Keep in mind that this anonymous module is present in the global scope.We can export the module by assigning it to a variable using expression, and then creating private and public encapsulation using the return statement. Consider below code:

We are doing following in above code snippet,

  1. Creating an IIFE.
  2. Assigning IIFE function to a variable
  3. Returning an anonymous object literal to create private and public encapsulation.

All properties of returned object would become public and can be accessed outside the module, however, any variable not part of the returned object cannot be accessed outside module. That is why for price we are getting 800 as the output, but, for color, value is undefined because it is private to the module1. Let us modify module1 to have more private and public properties, as shown in the listing below:

Read full article on the Infragistics blog

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s