How to define Singleton in TypeScript

前端 未结 20 758

What is the best and most convenient way to implement a Singleton pattern for a class in TypeScript? (Both with and without lazy initialisation).

20条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 20:28

    You can also make use of the function Object.Freeze(). Its simple and easy:

    class Singleton {
    
      instance: any = null;
      data: any = {} // store data in here
    
      constructor() {
        if (!this.instance) {
          this.instance = this;
        }
        return this.instance
      }
    }
    
    const singleton: Singleton = new Singleton();
    Object.freeze(singleton);
    
    export default singleton;
    

提交回复
热议问题