In JavaScript, the Singleton pattern is a design pattern that restricts the instantiation of a class to a single object. It is commonly used in scenarios where we need to ensure that only one instance of a class exists throughout the application.
Here’s an example of how to implement the Singleton pattern in JavaScript:
In this example, we create a Singleton
object with a private instance
variable that stores the instance of the class. We also define a private function createInstance()
that creates an object of the Singleton
class.
The public method getInstance()
is used to get the instance of the class. If instance
does not exist, it calls the createInstance()
function to create the instance, and then returns it.
The instance1
and instance2
variables both point to the same instance of the Singleton
class. The console.log()
statement outputs true
because they are the same instance.
Note that this implementation uses an Immediately Invoked Function Expression (IIFE) to define the Singleton
object. This is a common way to implement the Singleton pattern in JavaScript.