js 简单的单例写法

2019-06-06  本文已影响0人  章文顺

js 简单的单例写法

话不多说,上代码

let instance = null;

class TClass {
  public a: string;
  constructor(str) {
    if (!instance) {  // singleton-design pattern
      instance = this;
    }
    instance.a = str;

    return instance;
  }
}

// ------------------------------------------------

test('singleton-design test', t => {

  const a = new TClass('3');

  const b = new TClass('4');

  t.is(a.a, '4')

  t.is(a, b)
})

欢迎拍砖

大前端知识库收集分享 www.rjxgc.com 壹玖零Tech
搜罗各种前后端奇淫技巧,花式编程思想,日日更新,速来围观吧...

上一篇 下一篇

猜你喜欢

热点阅读