Learn how to Work With Singletons in JavaScript

The singleton is one of the most well-known design patterns. There are times when you need to have only one instance of a class and no more than that. This one class could be some kind of resource manager or some global lookup for values. This is where singletons come in.

In this article, you will take a look at what singletons are and how to best implement them in JavaScript.

Prerequisites

To successfully complete this tutorial, you will need the following:

  • An understanding of coding in JavaScript. If you need to expand your knowledge further in this area, check out this JavaScript series.
  • An understanding of how classes work in JavaScript. This Understanding Classes in JavaScript tutorial can provide this.

Understanding Singletons

Singletons are used to create an instance of a class if it does not exist or else return the reference of the existing one. This means that singletons are created exactly once during the runtime of the application in the global scope.

Based on this definition, singletons seem very similar to global variables. You might be wondering why singletons should be used in a coding language with global variables. There are a few things that make singletons different from global variables:

  • Global variables are lexically scoped whereas singletons are not. This means that if there is another variable with the same name as the global variable inside a programming block, then the first reference is given priority. Singletons, however, should not have that reference re-declared.
  • The value of a singleton is modified through methods.
  • The singleton is not freed until the termination of the program, which is likely not the case for a global variable.

Even in a language that supports global variables, singletons can be very useful. There are scenarios where singletons are handy. Some applications of singletons are logger objects or configuration settings classes.

Declaring Singletons

There are several ways to declare a singleton. This is one format you might see:

var SingletonInstance = {
 method1: function () { ... }
 method2: function () { ... }
};

 Copy

This singleton would be logged to the console like this:

console.log(SingletonInstance.method1());
console.log(SingletonInstance.method2());

 Copy

It’s good to keep in mind that this is not the best way to declare singletons. Another way would be to use a factory class that creates a singleton once.

var SingletonFactory = (function(){
  function SingletonClass() {
    // ...
  }

  var instance;

  return {
    getInstance: function(){
      if (!instance) {
        instance = new SingletonClass();
        delete instance.constructor;
      }
      return instance;
    }
  };
})();

 Copy

This is a better alternative to the first example because the class definition is private and the constructor is deleted after the first instance creation. This will prevent duplicate singletons from being created in the program. The drawback to this approach is that it’s very similar to the factory pattern.

There is still a third approach. This approach implements a combination of ES6 classes and the Object.freeze() method:script.js

class Singleton {
  constructor() {
   // ...
  }

  method1() {
    // ...
  }

  method2() {
    // ...
  }
}

const singletonInstance = new Singleton();

Object.freeze(singletonInstance);

 Copy

The Object.freeze() method prevents modification to properties and values of an object. So applying Object.freeze() to singletonInstance means you will not be able to change any of its properties or values later on in your code.

You can go further and write this singleton as a module and export it with the ES6 export functionality:script.js

export default singletonInstance;

 Copy

Then this singleton could be used in a separate file by importing it:otherFile.js

import mySingleton from './script.js';

mySingleton.method1();

 Copy

With these three approaches to creating singletons, choose which method fits best with your specific use case that allows for high readability.

Conclusion

It’s not always necessary to use singletons in your JavaScript code. Use singletons where it doesn’t affect the state of the application. This constraint severely limits their usage in big applications.

Jasca
Author: Jasca

Share This Post
Have your say!
00

Customer Reviews

5
0%
4
0%
3
0%
2
0%
1
0%
0
0%

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Thanks for submitting your comment!