I just read a few threads on the discussion of singleton design in javascript. I’m 100% new to the Design Pattern stuff but as I see since a Singleton by definition won’t have the need to be instantiated, conceptually if it’s not to be instantiated, in my opinion it doesn’t have to be treated like conventional objects which are created from a blueprint(classes). So my wonder is why not just think of a singleton just as something statically available that is wrapped in some sort of scope and that should be all.
From the threads I saw, most of them make a singleton though traditional javascript
new function(){}
followed by making a pseudo constructor.
Well I just think an object literal is enough enough:
var singleton = {
dothis: function(){},
dothat: function(){}
}
right? Or anybody got better insights?
[update] : Again my point is why don’t people just use a simpler way to make singletons in javascript as I showed in the second snippet, if there’s an absolute reason please tell me. I’m usually afraid of this kind of situation that I simplify things to much 😀
I agree with you, the simplest way is to use a object literal, but if you want private members, you could implement taking advantage of closures:
About the
new function(){}construct, it will simply use an anonymous function as aconstructor function, the context inside that function will be a new object that will be returned.Edit: In response to the @J5’s comment, that is simple to do, actually I think that this can be a nice example for using a Lazy Function Definition pattern:
When the function is called the first time, I make the object instance, and reassign
singletonto a new function which has that object instance in it’s closure.Before the end of the first time call I execute the re-defined
singletonfunction that will return the created instance.Following calls to the
singletonfunction will simply return theinstancethat is stored in it’s closure, because the new function is the one that will be executed.You can prove that by comparing the object returned:
The
==operator for objects will returntrueonly if the object reference of both operands is the same, it will return false even if the objects are identical but they are two different instances: