Simplest/cleanest way to implement a singleton in JavaScript

I think the easiest way is to declare a simple object literal:

var myInstance = {
  method1: function () {
    // ...
  },
  method2: function () {
    // ...
  }
};

If you want private members on your singleton instance, you can do something like this:

var myInstance = (function() {
  var privateVar = '';

  function privateMethod () {
    // ...
  }

  return { // public interface
    publicMethod1: function () {
      // All private members are accessible here
    },
    publicMethod2: function () {
    }
  };
})();

This has been called the module pattern, and it basically allows you to encapsulate private members on an object, by taking advantage of the use of closures.

If you want to prevent the modification of the singleton object, you can freeze it, using the ES5 Object.freeze method.

That will make the object immutable, preventing any modification to the its structure and values.

If you are using ES6, you can represent a singleton using ES Modules very easily, and you can even hold private state by declaring variables at the module scope:

// my-singleton.js
const somePrivateState = []

function privateFn () {
  // ...
}

export default {
  method1() {
    // ...
  },
  method2() {
    // ...
  }
}

Then you can simply import the singleton object to use it:

import myInstance from './my-singleton.js'
// ...

Leave a Comment