Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a JavaScript singleton with a constructor without using return?

Tags:

javascript

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?

like image 737
Tower Avatar asked Oct 10 '10 11:10

Tower


3 Answers

function Singleton() {
  if ( Singleton.instance )
    return Singleton.instance;
  Singleton.instance = this;
  this.prop1 = 5;
  this.method = function() {};
}​
like image 96
25 revs, 4 users 83% Avatar answered Sep 25 '22 01:09

25 revs, 4 users 83%


Here is my solution with closures:

function Singleton() {

    Singleton.getInstance = (function(_this) {
        return function() { return _this; };
    })(this);
}

Test:

var foo = new Singleton();
var bar = Singleton.getInstance();
foo === bar; // true
like image 35
katranci Avatar answered Sep 24 '22 01:09

katranci


If you are just looking for a place to initialise your singleton, how about this?

var singleton = {
    'pubvar': null,
    'init': function() {
        this.pubvar = 'I am public!';
        return this;
    }
}.init();

console.assert(singleton.pubvar === 'I am public!');

Simple and elegant.

like image 39
limouren Avatar answered Sep 25 '22 01:09

limouren