JavaScript – Singleton Design Pattern

SingleTon Design Pattern ImageSingleton design patterns ensures a class has only one instance and provide a global point to access it. Singleton pattern is handy when you want to create a class whose functionality does not required any changes for its multiple instances.

Basic Singleton implementation in JavaScript

A basic singleton pattern can be created using simple object literal, because the created object itself will be an instance.

Above example is very simple and easy to implement, but it is very limited as we cannot have private members in the object.

Singleton implementation with private members in the object

There are many ways of creating singleton design pattern. Depending on your specific need, If you don’t need private member then go with object literal approach.

But to have a private members, it is required to create a class and then expose a method within the class which always returns the same instance.

There are no classes in javascript. But, function can behave like a class in JavaScript.

A very simple singleton pattern implementation

Here, we have just created a self invoking function using the new keywords, that contains private and public data members.

Other way of implementing singleton pattern

Author: Gopal Juneja

A UX/UI enthusiast living in India Delhi having 18+ years of industry experience to use in beautiful design and handsome front end coding.

1 thought on “JavaScript – Singleton Design Pattern”

  1. I gave a talk on design patterns in JavaScript a few years ago at a meetup here in Manhattan, and the subject of whether these examples are “really” singletons or not came up. The object literal and the immediately invoked module pattern sufficiently capture the “spirit” of the singleton pattern, but sticklers would point out that these examples really aren’t analogous to a singleton in a more classic object-oriented language such as Java. I wrote a blog post talking about this nuance on my old, now defunct JavaScript blog… maybe I’ll try to rewrite it to illustrate what I’m talking about.

Leave a Reply

Your email address will not be published. Required fields are marked *