Simplest/Cleanest way to implement singleton in JavaScript?

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

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

30条回答
  •  别跟我提以往
    2020-11-22 05:24

    Isn't this a singleton too?

    function Singleton() {
        var i = 0;
        var self = this;
    
        this.doStuff = function () {
            i = i + 1;
            console.log( 'do stuff',i );
        };
    
        Singleton = function () { return self };
        return this;
    }
    
    s = Singleton();
    s.doStuff();
    

提交回复
热议问题