Simplest/Cleanest way to implement singleton in JavaScript?

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

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

30条回答
  •  庸人自扰
    2020-11-22 05:26

    Not sure why nobody brought this up, but you could just do:

    var singleton = new (function() {
      var bar = 123
    
      this.foo = function() {
        // whatever
      }
    })()
    

提交回复
热议问题