Jakub Arnold Jakub Arnold - 1 year ago 78
Javascript Question

Simplest/Cleanest way to implement singleton in JavaScript?

What is the simplest/cleanest way to implement singleton pattern in JavaScript?

CMS CMS
Answer Source

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 accesible here
    },
    publicMethod2: function () {
    }
  };
})();

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download