In JavaScript, I define a singleton class like this:
class Singleton {
constructor() {
if (!Singleton.instance) {
Singleton.instance = this
}
return Singleton.instance
}
}
And in TypeScript I write the singleton class like this:
class Singleton {
private static instance: Singleton
constructor() {
if (!Singleton.instance) {
Singleton.instance = this
}
return Singleton.instance
}
}
Are these valid ways of writing singleton classes in JavaScript and TypeScript?
How can I ensure that they are singletons?
Is there a better way to write singleton classes in JavaScript/TypeScript?
Aucun commentaire:
Enregistrer un commentaire