Simplest/Cleanest way to implement singleton in JavaScript?

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

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

30条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 05:23

    For me the cleanest way to do so is :

    const singleton = new class {
        name = "foo"
        constructor() {
            console.log(`Singleton ${this.name} constructed`)
        }
    }
    

    With this syntax you are certain your singleton is and will remain unique. You can also enjoy the sugarness of class syntax and use this as expected.

    (Note that class fields require node v12+ or a modern browser.)

提交回复
热议问题