BlackWolf
BlackWolf

Reputation: 5599

Singleton and Prototyping in Javascript

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.

Upvotes: 0

Views: 311

Answers (1)

user2864740
user2864740

Reputation: 61885

The proposed solution does not seem to "solve" anything1; as such, I recommend a standard variation of a "simple module pattern" using an idiomatic IIFE:

MySingleton = (function () {
    // This function is only executed once
    // and whatever is returned is the singleton.
    return {
       // Expose members here
    };
})();

Depending on specific need a new'ed object could also be returned, making this pattern flexible without the need to introduce a separate "singleton" field and guard, e.g.

MySingleton = (function () {
    // Contrived, but valid - any object returned
    // functions as the singleton.
    function MyClass {}
    return new MyClass();
})();

1If anything, it may lead to some "WTF?" moments when new MyClass() returns a shared/singleton object which is not "normal" behavior.

Upvotes: 1

Related Questions