JavaScript – The Singleton Pattern

The singleton design pattern is probably the simplest and most common pattern in JavaScript.

Why the singleton pattern?

  • Encapsulation of members & functions
  • Creates its own Namespace
  • A singleton is a single instance object
  • Encourages code reuse
  • Improves readability because you can logically organise your code

When to use a Singleton

The point of a singleton is to only have one instance. A shopping cart is a good example of something that you may want only a single instance of at one time.

Object Literals

The simplest form of Singleton is an object literal. This loose form of Singleton cannot be instantiated. All of the members are now accessible through the Singleton variable, accessible through dot notation.

var myCart = {
 self: this,
 totalCost: 0,
 totalQty: 0,
 cart: {},
 getCart: function(){ },
 updateCart: function(){ }
};

alert( "Total cost: $" + myCart.totalCost );

Public & Private Members using Closures

By using closures, we can create Private and Public Members and Functions. This pattern is more commonly called the Module Pattern.

var myCart = function(){
  // Private
  var self = this;
  var totalCost = 0;
  var totalQty = 0;
  var cart = {};

  return {
    // Public
    getCart: function(){ },
    updateCart: function(){ }
  };
}();