What is the simplest/cleanest way to implement singleton pattern in JavaScript?
Singleton:
Ensure a class has only one instance and provide a global point of access to it.
The Singleton Pattern limits the number of instances of a particular object to just one. This single instance is called the singleton.
The Singleton object is implemented as an immediate anonymous function. The function executes immediately by wrapping it in brackets followed by two additional brackets. It is called anonymous because it doesn't have a name.
Sample Program,
var Singleton = (function () {
var instance;
function createInstance() {
var object = new Object("I am the instance");
return object;
}
return {
getInstance: function () {
if (!instance) {
instance = createInstance();
}
return instance;
}
};
})();
function run() {
var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();
alert("Same instance? " + (instance1 === instance2));
}
run()