Simplest/Cleanest way to implement singleton in JavaScript?

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

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

30条回答
  •  借酒劲吻你
    2020-11-22 05:47

    I believe this is the simplest/cleanest and most intuitive way though it requires ES7:

    export default class Singleton {
    
      static instance;
    
      constructor(){
        if(instance){
          return instance;
        }
    
        this.state = "duke";
        this.instance = this;
      }
    
    }
    

    The source code is from: adam-bien.com

提交回复
热议问题