Simplest/Cleanest way to implement singleton in JavaScript?

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

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

30条回答
  •  悲哀的现实
    2020-11-22 05:32

    Simplest/Cleanest for me means also simply to understand and no bells & whistles as are much discussed in the Java version of the discussion:

    What is an efficient way to implement a singleton pattern in Java?

    The answer that would fit simplest/cleanest best there from my point of view is:

    https://stackoverflow.com/a/70824/1497139

    And it can only partly be translated to JavaScript. Some of the difference in Javascript are:

    • constructors can't be private
    • Classes can't have declared fields

    But given latest ECMA syntax it is possible to get close with:

    Singleton pattern as JavaScript class example

     class Singleton {
    
      constructor(field1,field2) {
        this.field1=field1;
        this.field2=field2;
        Singleton.instance=this;
      }
    
      static getInstance() {
        if (!Singleton.instance) {
          Singleton.instance=new Singleton('DefaultField1','DefaultField2');
        }
        return Singleton.instance;
      }
    }
    

    Example Usage

    console.log(Singleton.getInstance().field1);
    console.log(Singleton.getInstance().field2);
    

    Example Result

    DefaultField1
    DefaultField2
    

提交回复
热议问题