美文网首页
js 简单的单例写法

js 简单的单例写法

作者: 章文顺 | 来源:发表于2019-06-06 17:48 被阅读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
搜罗各种前后端奇淫技巧,花式编程思想,日日更新,速来围观吧...

相关文章

网友评论

      本文标题:js 简单的单例写法

      本文链接:https://www.haomeiwen.com/subject/beiuxctx.html