Simplest/Cleanest way to implement singleton in JavaScript?

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

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

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

    The following works in node v6

    class Foo {
      constructor(msg) {
    
        if (Foo.singleton) {
          return Foo.singleton;
        }
    
        this.msg = msg;
        Foo.singleton = this;
        return Foo.singleton;
      }
    }
    

    We test:

    const f = new Foo('blah');
    const d = new Foo('nope');
    console.log(f); // => Foo { msg: 'blah' }
    console.log(d); // => Foo { msg: 'blah' }
    

提交回复
热议问题