Simplest/Cleanest way to implement singleton in JavaScript?

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

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

30条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 05:35

    There is more than one ways to skin a cat :) Depending on your taste or specific need you can apply any of the proposed solutions. I personally go for CMS' first solution whenever possible (when you don't need privacy). Since the question was about the simplest and cleanest, that's the winner. Or even:

    var myInstance = {}; // done!
    

    This (quote from my blog) ...

    var SingletonClass = new function() { 
        this.myFunction() { 
            //do stuff 
        } 
        this.instance = 1; 
    }
    

    doesn't make much sense (my blog example doesn't either) because it doesn't need any private vars, so it's pretty much the same as:

    var SingletonClass = { 
        myFunction: function () { 
            //do stuff 
        },
        instance: 1 
    }
    

提交回复
热议问题