Simplest/Cleanest way to implement singleton in JavaScript?

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

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

30条回答
  •  旧时难觅i
    2020-11-22 05:40

    If you want to use classes:

    class Singleton {
      constructor(name, age) {
        this.name = name;
        this.age = age;
        if(this.constructor.instance)
          return this.constructor.instance;
        this.constructor.instance = this;
      }
    }
    let x = new Singleton('s',1);
    let y = new Singleton('k',2);
    

    Output for the above will be:

    console.log(x.name,x.age,y.name,y.age) // s 1 s 1
    

    Another way of writing Singleton using function

    function AnotherSingleton (name,age) {
      this.name = name;
      this.age = age;
      if(this.constructor.instance)
        return this.constructor.instance;
      this.constructor.instance = this;
    }
    
    let a = new AnotherSingleton('s',1);
    let b = new AnotherSingleton('k',2);
    

    Output for the above will be:

    console.log(a.name,a.age,b.name,b.age)// s 1 s 1
    

提交回复
热议问题