tags:

views:

34

answers:

2

Hi,

I currently know two ways to construct singletons in JavaScript. First:

var singleton = {
 publicVariable: "I'm public",
 publicMethod: function() {}
};

It is perfect except that it does not have a constructor where I could run initialization code.

Second:

(function() {

var privateVariable = "I'm private";
var privateFunction = function() {}

return {
 publicVariable: "I'm public",
 publicMethod: function () {}
}

})();

The first version does not have private properties nor does it have a constructor, but it is faster and simpler. The second version is more complex, ugly, but has a constructor and private properties.

I'm not in a need for private properties, I just want to have a constructor. Is there something I am missing or are the two approaches above the only ones I've got?

+1  A: 
function Singleton() {
  if ( Singleton.instance )
    return Singleton.instance;
  Singleton.instance = this;
  this.prop1 = 5;
  this.method = function() {};
}​
galambalazs
A: 
var singleton = new function() {  // <<----Notice the new here
  //constructorcode....

  this.publicproperty ="blabla";
}

This is basically the same as creating a function, then instantly assiging a new instace of it to the variable singleton. Like var singleton = new SingletonObject();

I highly advice against using singletons this way in javscript though because of the execution order is based on where in the file you place the object and not on your own logic.

snowandice