I was just looking into ways of defining singletons in JavaScript, and after looking into a few samples I thought about the following way which I haven't found anywhere:
function MyClass() {
if (MyClass._sharedInstance === undefined) {
// actual constructor code
MyClass._sharedInstance = this;
}
return MyClass._sharedInstance;
}
MyClass._sharedInstance = undefined;
Seems to work fine... but the fact that I couldn't find this anywhere makes me suspicious. Is there any reason not to do a singleton that way, especially considering the many little pitfalls of JavaScript. I know that by simply doing a var MyClass = { /* MyClass Stuff */ }
I can achieve a singleton with less code, but for the sake of consistency I would like to define all my classes using prototypes.