Singleton function in JavaScript

Neeraj Singh

By Neeraj Singh

on 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.

1var Logger = function (path) {
2  this.path = path;
3};
4
5l1 = new Logger("/home");
6console.log(l1);
7
8l2 = new Logger("/dev");
9console.log(l2);
10
11console.log(l1 === l2);

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

Singleton solution using a global variable

1window.global_logger = null;
2var Logger = function (path) {
3  if (global_logger) {
4    console.log("global logger already present");
5  } else {
6    this.path = path;
7    window.global_logger = this;
8  }
9  return window.global_logger;
10};
11
12l1 = new Logger("/home");
13console.log(l1);
14
15l2 = new Logger("/dev");
16console.log(l2);
17
18console.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

1var Logger = (function () {
2  var _instance;
3
4  return function (path) {
5    if (_instance) {
6      console.log("an instance is already present");
7    } else {
8      this.path = path;
9      _instance = this;
10    }
11
12    return _instance;
13  };
14})(); //note that it is self invoking function
15
16var l1 = new Logger("/root");
17console.log(l1);
18
19var l2 = new Logger("/dev");
20console.log(l2);
21
22console.log(l1 === l2);

This solution does not pollute global namespace.

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.