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

function Singleton() {
  if ( Singleton.instance )
    return Singleton.instance;
  Singleton.instance = this;
  this.prop1 = 5;
  this.method = function() {};
}​

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

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.

Tags:

Javascript