Question 49
Question
Can you explain how to implement a singleton pattern in JavaScript using closures?
Answer
The singleton pattern ensures that only one instance of a class is ever created. Here's how to implement it effectively in JavaScript using closures:
Explanation:
Immediately Invoked Function Expression (IIFE): The code is wrapped in an IIFE
(function() { ... })()
. This creates a private scope, preventing accidental external access to variables within the closure.instance
Variable: Alet
variableinstance
is declared inside the IIFE. It's initially undefined and will hold the singleton instance once created.init()
Function: This function (optional) initializes any properties or methods that your singleton needs when it's first created.Returned Constructor-like Function: The IIFE returns another function. This returned function acts as the constructor for the singleton pattern.
Singleton Logic: Inside the returned function:
if (!instance)
checks if an instance already exists. If not, it creates a new empty object (instance
) and callsinit()
to initialize it.In either case, it returns the existing or newly created
instance
.
Benefits of Closures for Singleton:
Encapsulation: The closure hides the internal workings of the singleton from outside code, making it more robust.
Controlled Access: You can explicitly control how the singleton is accessed through the returned constructor function.
Last updated