mardi 30 juillet 2019

How to ensure a class is a singleton in JavaScript/TypeScript? And best way to write singleton class?

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