码迷,mamicode.com
首页 > Web开发 > 详细

js 单例模式

时间:2020-03-13 12:46:58      阅读:52      评论:0      收藏:0      [点我收藏+]

标签:struct   单例   name   cto   pre   return   private   模式   stat   

使用静态属性保存第一次示例对象,在以后的实例中,都将返回这个。

class Ajanuw {
  static __self?: Ajanuw;
  constructor(public name: string) {
    return this.__Ajanuw();
  }

  private __Ajanuw() {
    if (!Ajanuw.__self) {
      Ajanuw.__self = this;
    }
    return Ajanuw.__self;
  }
}

let a = new Ajanuw("ajanuw");
console.log(a.name); // ajanuw

let b = new Ajanuw("bbb");
console.log(a.name); // ajanuw

js 单例模式

标签:struct   单例   name   cto   pre   return   private   模式   stat   

原文地址:https://www.cnblogs.com/ajanuw/p/12485632.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!