Collected from various sources, here is a recollection of various singleton methods

The simple

var singleton = {};

The elegant


function singleton() {
var instance = (function() {
var privateVar;

function privateMethod () {
// ...
}

return { // public interface
publicMethod1: function () {
// private members can be accessed here
},
publicMethod2: function () {
// ...
}
};
})();

singleton = function () { // re-define the function for subsequent calls
return instance;
};

return singleton(); // call the new function
}

The spec informed
var SingletonClass = (function() {
var instance;
function SingletonClass() {
if (instance == null) {
instance = Object.create(SingletonClass.prototype);
}

return instance;
}

return {
getInstance: function() {
return new SingletonClass();
}
};
})();

var x = SingletonClass.getInstance();
var y = SingletonClass.getInstance();
var z = new x.constructor();

The Freaked out


(function (global) {

var singleton;

function Singleton () {
// singleton does have a constructor that should only be used once
this.foo = "bar";
delete Singleton; // disappear the constructor if you want
}

global.singleton = function () {
return singleton || (singleton = new Singleton());
};

})(window);

Categories: javascript

Comments are closed.