TypeScript: 创建单例

在创建单例时,你可能会偷懒创建下面这样的代码

class A {
  static ins: A;
  arr = [];
  constructor() {
    return (A.ins ??= this);
  }
}

上面的代码能创建单例,但是你却发现编译后的es6代码却是这鸟样

class A {
    constructor() {
        var _a;
        this.arr = [];
        return ((_a = A.ins) !== null && _a !== void 0 ? _a : (A.ins = this));
    }
}

在之后每次都会创建一个毫无卵用的空数组,然后丢弃...

还是老老实实写单例吧

class A {
  static ins: A;
  arr!: any[];

  constructor() {
    if (A.ins) return A.ins;

    this.arr = [];
    return (A.ins = this);
  }
}

编译后的es6

class A {
    constructor() {
        if (A.ins)
            return A.ins;
        this.arr = [];
        return (A.ins = this);
    }
}

期待以后TypeScript能出factory关键词来优化单例的创建

posted @ 2021-09-13 20:21  Ajanuw  阅读(111)  评论(0编辑  收藏  举报