1

In what scenario do we need to implement Singleton Class in javascript as below

var Singleton = (function () {
    var instance;

    function createInstance() {
        var object = new Object("I am the instance");
        return object;
    }

    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();

function run() {

    var instance1 = Singleton.getInstance();
    var instance2 = Singleton.getInstance();

    alert("Same instance? " + (instance1 === instance2));  
}
collapsar
  • 17,010
  • 4
  • 35
  • 61
Akash
  • 11
  • 1

1 Answers1

0

The singleton pattern is a design pattern that restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects. The term comes from the mathematical concept of a singleton.

The simplest singleton implementation in JavaScript is:

var Singleton = {};

What are the benefits we get from this implementation:

  1. It instantiates only a single object
  2. It is safe – it keeps the reference to the singleton inside a variable, which lives inside a lexical closure and is not accessible by the outside world
  3. It allows you to initialize the singleton with some arguments. The module pattern, which wraps the singleton is not aware of the initialization arguments – it simply forwards the call with apply
  4. You can use the instanceof operator
backtrack
  • 7,996
  • 5
  • 52
  • 99
  • "*It allows you to initialize the singleton with some arguments.*" doesn't really make sense. If it's a singleton, there is only one valid way to initialise it, so you would just hardcode that. – Bergi Feb 08 '18 at 05:17