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:

const Singleton = (function() {
  let instance; 

  function init() {
    console.log("Singleton instance created!");
    // Initialize any properties or methods here if needed
  }

  return function() { // Returned function acts as the constructor
    if (!instance) {
      instance = {}; // Create the singleton object
      init();             // Call initialization only once
    }
    return instance; 
  };
})();

// Accessing and using the singleton:
const firstInstance = Singleton(); 
const secondInstance = Singleton(); 

console.log(firstInstance === secondInstance); // Output: true (They both reference the same object)

Explanation:

  1. 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.

  2. instance Variable: A let variable instance is declared inside the IIFE. It's initially undefined and will hold the singleton instance once created.

  3. init() Function: This function (optional) initializes any properties or methods that your singleton needs when it's first created.

  4. Returned Constructor-like Function: The IIFE returns another function. This returned function acts as the constructor for the singleton pattern.

  5. Singleton Logic: Inside the returned function:

    • if (!instance) checks if an instance already exists. If not, it creates a new empty object (instance) and calls init() 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