What is the simplest/cleanest way to implement singleton pattern in JavaScript?
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.)