单例模式是一种设计模式,他主要是用来限制一个类只能创建一个对象,而不是每次创建新的对象
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。