Simplest/Cleanest way to implement singleton in JavaScript?

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

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

30条回答
  •  生来不讨喜
    2020-11-22 05:35

    I think the cleanest approach is something like:

    var SingletonFactory = (function(){
        function SingletonClass() {
            //do stuff
        }
        var instance;
        return {
            getInstance: function(){
                if (instance == null) {
                    instance = new SingletonClass();
                    // Hide the constructor so the returned object can't be new'd...
                    instance.constructor = null;
                }
                return instance;
            }
       };
    })();
    

    Afterwards, you can invoke the function as

    var test = SingletonFactory.getInstance();
    

提交回复
热议问题