views:

1238

answers:

3

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

+22  A: 

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.

CMS
+1 Nicely done.
Andrew Hare
Thanks @Andrew!
CMS
+1 Isn't it a bit strange to look for a "Singleton pattern" in a language with global variables???
Victor
+1  A: 

How about this, the variable called 'hidden' is private and cannot be replaced because it is hidden within a closure.

var singleton = {


// private object

var hidden = { id = 5 }; // wherever you want
return {
   getInstance: function() { return hidden; }
};
}();
BeWarned