[JavaScript] 单例模式
特点 | 一个类只能构造出唯一实例 |
条件 |
1.确保只有一个实例 ; 2.可以全局访问 |
适用 |
适用于弹框的实现, 全局缓存 |
实现单例模式
const singleton = function(name) {
this.name = name
this.instance = null
}
singleton.prototype.getName = function() {
console.log(this.name)
}
singleton.getInstance = function(name) {
if (!this.instance) { // 关键语句
this.instance = new singleton(name)
}
return this.instance
}
// test
const a = singleton.getInstance('a') // 通过 getInstance 来获取实例
const b = singleton.getInstance('b')
console.log(a === b)
弹框层的实践
const createLoginLayer = function() {
const div = document.createElement('div');
div.innerHTML = '登入浮框';
div.style.display = 'none';
document.body.appendChild(div);
return div;
}
const getSingle = function(fn) {
let result;
return function() {
return result || (result = fn.apply(this, arguments));
}
}
const createSingleLoginLayer = getSingle(createLoginLayer);
document.getElementById('loginBtn').onclick = function() {
let loginLayer = createSingleLoginLayer();
if( createSingleLoginLayer().style.display == "none" ){
loginLayer.style.display = 'block';
}else{
loginLayer.style.display = 'none';
}
}