Reputation: 412
Everywhere I saw an implementation of singleton in javascript in a such manner:
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;
}
};
})();
Here we can see that it returns a function which we must call in order to get an object. Question: Why we can't just write like this:
var Singleton = (function () {
function privateMethod() {
...
}
return {
publicMethod1: function() { },
publicMethod2: function() { },
};
})();
Somebody will say that reason is for inheritance support. However, I don't see a difference. Anyway Singleton is an object now.
Upvotes: 5
Views: 92
Reputation: 4860
Interesting question, and I'll try a guess.
I see a few reasons:
first is pointed by @Steffomio in the comments.
First version will be instanciated only at the first usage, while second will be instanciated immediately, which could lead to CPU pressure on page load (often an unwanted effect)
second is here:
if (!instance) {
instance = createInstance();
}
return instance;
part of the code.
With your version of the code (simple closure evaluation), it could fail if the singleton's script is embedded several times in the webpage.
The first time the singletong will be created, then some line of code modifies it, then another recreates the singleton, and prior modifications are lost.
third reason is that many languages can't express auto evaluated functions as easily as in JavaScript. If you look at how to implement a singleton in C#, you'll find a similar pattern, which is probably often translated as is in JavaScript.
final reason is inheritance support, as you stated yourself.
Upvotes: 2
Reputation: 262
You can use the module revealing pattern like this.
var Singleton = Singleton || function () {
var privateMethod1 = function() {
...
}
var privateMethod2 = function() {
...
}
return {
publicMethod1: privateMethod1,
publicMethod2: privateMethod2
};
}();
The way closure works, this method will be loaded only once in your application and it will keep a reference to your methods.
You don't need to make a instance of Singleton (new Singleton --> not needed)
You can call it directly Singleton.publicMethod1()
Upvotes: 0