Singleton function in JavaScript

Neeraj Singh avatar

Neeraj Singh

April 11, 2010

Recently I was discussed with a friend how to create a singleton function in JavaScript. I am putting the same information here in case it might help someone understand JavaScript better.

Creating an Object

Simplest solution is creating an instance of the object.

var Logger = function (path) {
  this.path = path;
};

l1 = new Logger("/home");
console.log(l1);

l2 = new Logger("/dev");
console.log(l2);

console.log(l1 === l2);

Above solution works. However l2 is a new instance of Logger .

Singleton solution using a global variable

window.global_logger = null;
var Logger = function (path) {
  if (global_logger) {
    console.log("global logger already present");
  } else {
    this.path = path;
    window.global_logger = this;
  }
  return window.global_logger;
};

l1 = new Logger("/home");
console.log(l1);

l2 = new Logger("/dev");
console.log(l2);

console.log(l1 === l2);

Above solution works. However this solution relies on creating a global variable. To the extent possible it is best to avoid polluting global namespace.

Single solution without polluting global namespace

var Logger = (function () {
  var _instance;

  return function (path) {
    if (_instance) {
      console.log("an instance is already present");
    } else {
      this.path = path;
      _instance = this;
    }

    return _instance;
  };
})(); //note that it is self invoking function

var l1 = new Logger("/root");
console.log(l1);

var l2 = new Logger("/dev");
console.log(l2);

console.log(l1 === l2);

This solution does not pollute global namespace.

Follow @bigbinary on X. Check out our full blog archive.