Implementing Singleton Pattern in Javascript

In singleton pattern, one instance of a class will be instantiated and no more. The same object is returned to all the clients that request for a new object of a singleton class. In traditional object oriented languages, this is achieved by making the constructor private and exposing a static public property which in turn returns the same instance every time.

Let’s see how this is done in javascript:

The public method getInstance() exposes the object instance. A check is done to see if an instance was created earlier. If it was created before, that same instance is used; otherwise a new instance is created and returned.

The init() function exposes the public and private methods of the instance. Private methods and properties are protected from outside access. Public methods and properties are accessible from outside, just like any other modules.

The singleton pattern is not very useful in the context of javascript in traditional webpages, as the application scope gets reset every time the page is refreshed.

However, the singleton implementations come particularly handy in Singe Page Applications commonly referred as SPA. In a SPA, the entire lifetime of the application is managed in a single page and there are no page refreshes that reset the application life cycle.

Module Pattern In Javascript

Module pattern allows to emulate the concept of classes in Javascript. It allows to create private methods and variables along with their public counterparts inside the same class, thus shielding particular parts of the class from the global scope.

Let’s look at an example:

Here, the private variable ‘random’ is encapsulated and any code outside of the module can’t access this variable. The functions and properties inside the ‘return{ }’ are exposed publicly and anything outside of ‘return{ }’ are considered private.

This is can also be written as a self-contained module:

Notice the () at the end of the module definition? This will create an instance and return it in the global variable ‘module’.

Passing arguments

A variation of this pattern allows to import modules and alias them locally by passing it as arguments to the anonymous function.

Let’s look at another example:

Here, the global variable jQuery is passed as ‘jq’ into the module making it local inside the scope of the module.

Reference:
From the excellent online book by Addy Osmani:
Learning Javascript Design Patterns