单例模式:确保只有一个实例,并提供全局访问。
常用单例模式:
1)代理单例模式
var CreateDiv = funnction(html){
this.html = html;
this.init();
}
CreateDiv.prototype.init = function(){
var oDiv = document.createElement('div');
oDiv.innerHTML = this.html;
document.body.appendChild(oDiv);
};
引入代理类proxySingleCreateDiv(管理单例逻辑)
var proxySingleCreateDiv = (function(){
var instance;
return function(html){
if(!instance){
instance = new CreateDiv();
}
return instance;
}
})();
var test1 = new proxySingleCreateDiv('test1');
var test2 = new proxySingleCreateDiv('test2');
console.log(test1 === test2);//true
instance实例对象在调用new proxySingleCreateDiv()时才被创建,而不是在页面加载好时就被创建。
2)通用惰性单例模式(如某个弹窗在页面是唯一的,不可能同时出现两个该弹窗)
var Single = function(fn){ //管理单例逻辑,result身在闭包中,永远不会被销毁
var result;
return function(){
return result||(result = fn.apply(this,arguments));
}
};
var CreateDiv = function(){
var oDiv = document.createElement('div');
oDiv.innerHTML = '弹窗';
oDiv.style.display = 'none';
document.body.appendChild(oDiv);
return oDiv;
};
$('#login').click(function(){
var disdiv = Single(CreateDiv)();
disdiv.style.display = 'block';
})