保证一个类只有一个实例,并且提供一个访问该实例的全局节点,在Element-ui中的loading用到了单例模式,也就是实现了一个全局的loading遮罩层,但是限制用户同一时刻只能调用一个loading,如果不限制的话,连续调用两次,第二个遮罩层就会覆盖住第一个,就会出现bug,下面就是单例模式的js实现
const Singleton = function () {
this.instance = null;
};
Singleton.getInstance = function () {
if (!this.instance) {
this.instance = new Singleton();
}
return this.instance;
};
const a = Singleton.getInstance();
const b = Singleton.getInstance();
console.log(a === b);
此时,a和b是相等的,因为全局只创建了一个实例