类的单例模式

单例模式是一种设计模式,他主要是用来限制一个类只能创建一个对象,而不是每次创建新的对象

class ChatStore {
  message= [];
  init = () =>{};
  updateMsg = () => {};

  static destroy() {
    this._instance = null;
  }

  static get instance() {
    if (!this._instance) {
      this._instance = new ChatStore();
    }
    return this._instance;
  }
}
ChatStore.instance === ChatStore.instance; // true
new ChatStore() === new ChatStore(); // false

ChatStore.instance是一个单例的模式,无论多少次调用ChatStore.instance,都只会初始化一次,因此ChatStore.instance === ChatStore.instance 总是返回 true。

而new ChatStore()每次调用都会生成一个全新的ChatStore对象,这两个对象在内存中存放的位置不同。所以new ChatStore() === new ChatStore() 总是返回 false。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容