What is the simplest/cleanest way to implement singleton pattern in JavaScript?
You can do it with decorators like in this example below for TypeScript:
class YourClass {
@Singleton static singleton() {}
}
function Singleton(target, name, descriptor) {
var instance;
descriptor.value = () => {
if(!instance) instance = new target;
return instance;
};
}
Then you use your singleton like this:
var myInstance = YourClass.singleton();
As of this writing, decorators are not readily available in JavaScript engines. You would need to make sure your JavaScript runtime has decorators actually enabled or use compilers like Babel and TypeScript.
Also note that singleton instance is created "lazy", i.e., it is created only when you use it for the first time.