Revisiting The JavaScript Singleton Pattern

JavaScript design patterns are quite good examples to sharpen your JavaScript skills. Let's take a look at the singleton pattern.

I'm currently reading Addy Osmani’s book about JavaScript design patterns. It's a very interesting introduction and I strongly recommend you this read. Viewing his Singleton Pattern implementation i had two simple ideas of improvement to get them more powerful. Here is a basic implementation of this pattern :

To the Addy's implementation I just added a fake constructor in order to prevent misuses of the singleton pattern. As you can see, the Singleton pattern purpose is to ensure there will always be only one instance of it's "class".

After reading it I wondered if there could be a way to make singletons inherance possible. I finally got it by adding a simple snippet to the previous implementation

As you can see our singleton inherits from the parent constructor we have given it. It also can take a conventional objet constructor or another singleton.

The main use case for it is the ability to extend to another conventional constructor the singleton pattern. It also provide a way to extend existing singletons and change their behavior with no risk to alter them.

< Blog