Singleton 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.
1 2 3 4 5 6 7 8 |
var singleTon = { name: "Reality On Web", location: "Delhi", getInfo: function() { console.log(singleTon.name); console.log(singleTon.location); } } |
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.
1 |
var myObject = { }; // Singleton is done as in the above example |
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
1 2 3 4 5 6 7 |
var singleton = new (function() { var bar = 3; this.foo = function() { // whatever } })() |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
var singleTon = (function() { var privateVar = ''; function privateMethod () { // ... } return { // this is your public interface publicMethod1: function () { // all private members are accessible here }, publicMethod2: function () { // all private members are accessible here } }; })(); |
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.