What is the simplest/cleanest way to implement singleton pattern in JavaScript?
I think the cleanest approach is something like:
var SingletonFactory = (function(){
function SingletonClass() {
//do stuff
}
var instance;
return {
getInstance: function(){
if (instance == null) {
instance = new SingletonClass();
// Hide the constructor so the returned object can't be new'd...
instance.constructor = null;
}
return instance;
}
};
})();
Afterwards, you can invoke the function as
var test = SingletonFactory.getInstance();
In es6
:
class Singleton {
constructor () {
if (!Singleton.instance) {
Singleton.instance = this
}
// Initialize object
return Singleton.instance
}
// Properties & Methods
}
const instance = new Singleton()
Object.freeze(instance)
export default instance
There is more than one ways to skin a cat :) Depending on your taste or specific need you can apply any of the proposed solutions. I personally go for CMS' first solution whenever possible (when you don't need privacy). Since the question was about the simplest and cleanest, that's the winner. Or even:
var myInstance = {}; // done!
This (quote from my blog) ...
var SingletonClass = new function() {
this.myFunction() {
//do stuff
}
this.instance = 1;
}
doesn't make much sense (my blog example doesn't either) because it doesn't need any private vars, so it's pretty much the same as:
var SingletonClass = {
myFunction: function () {
//do stuff
},
instance: 1
}
I deprecate my answer, see my other one.
Usually module pattern (see CMS' answer) which is NOT singleton pattern is good enough. However one of the features of singleton is that its initialization is delayed till object is needed. Module pattern lacks this feature.
My proposition (CoffeeScript):
window.singleton = (initializer) ->
instance = undefined
() ->
return instance unless instance is undefined
instance = initializer()
Which compiled to this in JavaScript:
window.singleton = function(initializer) {
var instance;
instance = void 0;
return function() {
if (instance !== void 0) {
return instance;
}
return instance = initializer();
};
};
Then I can do following:
window.iAmSingleton = singleton(function() {
/* This function should create and initialize singleton. */
alert("creating");
return {property1: 'value1', property2: 'value2'};
});
alert(window.iAmSingleton().property2); // "creating" will pop up; then "value2" will pop up
alert(window.iAmSingleton().property2); // "value2" will pop up but "creating" will not
window.iAmSingleton().property2 = 'new value';
alert(window.iAmSingleton().property2); // "new value" will pop up
I think I have found the cleanest way to program in JavaScript, but you'll need some imagination. I got this idea from a working technique in the book "javascript the good parts".
Instead of using the new keyword, you could create a class like this:
function Class()
{
var obj = {}; // Could also be used for inheritence if you don't start with an empty object.
var privateVar;
obj.publicVar;
obj.publicMethod= publicMethod;
function publicMethod(){}
function privateMethod(){}
return obj;
}
You can instantiate the above object by saying:
var objInst = Class(); // !!! NO NEW KEYWORD
Now with this work method in mind you could create a singleton like this:
ClassSingleton = function()
{
var instance= null;
function Class() // This is the class like the above one
{
var obj = {};
return obj;
}
function getInstance()
{
if( !instance )
instance = Class(); // Again no new keyword;
return instance;
}
return { getInstance : getInstance };
}();
Now you can get your instance by calling
var obj = ClassSingleton.getInstance();
I think this is the neatest way as the complete "Class" is not even accessible.
Here is the simple example to explain singleton pattern in javascript.
var Singleton=(function(){
var instance;
var init=function(){
return {
display:function(){
alert("This is a Singleton patern demo");
}
};
};
return {
getInstance:function(){
if(!instance){
alert("Singleton check");
instance=init();
}
return instance;
}
};
})();
// In this call first display alert("Singleton check")
// and then alert("This is a Singleton patern demo");
// It means one object is created
var inst=Singleton.getInstance();
inst.display();
// In this call only display alert("This is a Singleton patern demo")
// it means second time new object is not created,
// it uses the already created object
var inst1=Singleton.getInstance();
inst1.display();