Simplest/Cleanest way to implement singleton in JavaScript?

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

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

30条回答
  •  别那么骄傲
    2020-11-22 05:35

    In es6:

    class Singleton {
      constructor () {
        if (!Singleton.instance) {
          Singleton.instance = this
        }
        // Initialize object
        return Singleton.instance
      }
      // Properties & Methods
    }
    
    const instance = new Singleton()
    Object.freeze(instance)
    
    export default instance
    

提交回复
热议问题