Blogger Ever

Javascript object oriented behaviour: The singleton pattern

Design pattern simplifies our common problems and let us code in standard way. Singleton is one the helpful and important design pattern in Javascript.

Among various Javascript patterns, singleton is one of the popular design pattern that is used around. Basically design patterns are the basic solutions to commonly occurring problems in Javascript. Singleton, as referred by name is something that is something refers to "single". Well, it is defined as a design pattern which make sure that there should be only one instance of a class and we can access it globally. Why do we use something like that right? Lets find in this post.

The reason of using singleton design pattern is to control certain actions right from one class and not let outside world interfere with it. The way it does is by securing it from global namespace pollution. There are many libraries involves in an app, with tons of namespaces, therefore association of certain methods to one class secures it from being accessed from outside.

One way that singleton is helpful is: certain values which are required access globally while you want them private. Singleton gives you that easily because all the time an instance is created (every time same instance is returned), then changing values automatically changes all the values. Here is how reference works, check this gif below.

The singleton object executes an anonymous function immediately by adding two additional brackets at the end. 
var singleton=(function(){
  // Coding goes here...
This way we have singleton class. Now lets add some 
var party = (function() {
  var instance; // The variable to store instance

  // Add party stuff
  function start_party() {
    // Private variables
    var drinks = 5;
    var lights = true;
    // Private methods
    var add_drinks = function(more) {
        drinks = drinks + more;
      // different method for returning value
    var get_drinks = function() {
      return drinks;
    return {
      drinks: drinks,
      lights: lights,
      add_drinks: add_drinks,
      get_drinks: get_drinks
  // Create and then return instance
  // if one do not exist
  return {
    getInstance: function() {
      if (!instance) {
        instance = start_party();
      return instance;
Good thing is, everything is under control from and place and not just that, we can change values from central. Here is what it looks in action.
var party_1 = party.getInstance();
console.log(party_1.drinks); // 5
var party_2 = party.getInstance();
party_2.add_drinks(5); // drinks added
console.log(party_1.get_drinks()); // 10
This is one of the important design patter, I will try to post more. 

2013-2016 Copyright Blogger E\ver . Coded, managed and founded by Mohammad Hamza (@hamzadhamiya) . Hosted on Blogger and fonts used are Raleway and Open Sans.