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.
To successfully complete this tutorial, you will need the following:
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:
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.
There are several ways to declare a singleton. This is one format you might see:
var SingletonInstance = {
method1: function () { ... }
method2: function () { ... }
};
This singleton would be logged to the console like this:
console.log(SingletonInstance.method1());
console.log(SingletonInstance.method2());
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;
}
};
})();
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:
class Singleton {
constructor() {
// ...
}
method1() {
// ...
}
method2() {
// ...
}
}
const singletonInstance = new Singleton();
Object.freeze(singletonInstance);
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:
export default singletonInstance;
Then this singleton could be used in a separate file by importing it:
import mySingleton from './script.js';
mySingleton.method1();
With these three approaches to creating singletons, choose which method fits best with your specific use case that allows for high readability.
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.
With this fundamental design pattern in your tool kit, you may want to explore factory patterns in JavaScript. If you’re interested in learning more about state management, check out these articles on state management in React with Redux and state management with React hooks.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Sign up for Infrastructure as a Newsletter.
Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
“It’s good to keep in mind that this is not the best way to declare singletons.”
Why? I really don’t like stating an opinion in an article like this and providing 0 arguments for backing it up.
That was quite tasteful information. That helped me to understand the singleton pattern. Thanks