Simplest/Cleanest way to implement singleton in JavaScript?

后端 未结 30 1064
名媛妹妹
名媛妹妹 2020-11-22 05:17

What is the simplest/cleanest way to implement singleton pattern in JavaScript?

30条回答
  •  孤独总比滥情好
    2020-11-22 05:34

    Singleton:

    Ensure a class has only one instance and provide a global point of access to it.

    The Singleton Pattern limits the number of instances of a particular object to just one. This single instance is called the singleton.

    • defines getInstance() which returns the unique instance.
    • responsible for creating and managing the instance object.

    The Singleton object is implemented as an immediate anonymous function. The function executes immediately by wrapping it in brackets followed by two additional brackets. It is called anonymous because it doesn't have a name.

    Sample Program,

    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));  
    }
    
    run()

提交回复
热议问题