javascript单例形式总结
1.什么是单例形式?
单例形式的定义是:一个类唯一一个实例,而且能够在全局接见
。
在一样平常开辟中,单例形式的运用非常普遍。比方开辟登录浮窗,我们不管点击登录按钮多少次,浮窗都只会建立一次。
这时候,浮窗就很合适运用单例形式来建立。
2.完成单例形式
var CreatePopbox = function(html){
this.html = html;
this._init();
};
CreatePopbox.prototype._init = function(){
this.div = document.createElement('div');
this.div.innerHTML = this.html;
this.div.style.display = 'none';
document.body.appendChild(this.div);
};
CreatePopbox.prototype.show = function(){
this.div.style.display = 'block';
};
CreatePopbox.prototype.hide = function(){
this.div.style.display = 'none';
};
//经由过程代办函数到达单例形式的结果
var proxysingleCreatePopbox = (function(){
var instance;
return function(html){
if(!instance){
instance = new CreatePopbox(html);
}
return instance;
}
})();
//建立CreatePopbox:
var a = new proxysingleCreatePopbox("this is a");
var b = new proxysingleCreatePopbox("this is b");
console.log(a === b); //true
能够看到,a和b都指向了同一个实例,实行new proxysingleCreatePopbox("this is b")
时,并不会从新天生一个新的CreatePopbox
。
这相符了单例形式的中心:确保实例只要一个
。
经由过程以上例子,我们已相识单例形式的完成体式格局,但另有一些缺点:
建立对象和单例治理的逻辑都合在
proxysingleCreatePopbox
里边,当须要建立其他单例时,只能把proxysingleCreatePopbox
拷贝一次。
因而,我们须要把代码再革新一下,把稳定的部份断绝出来。
//
var getSingle = function(fn){
var singleObj;
return function(obj){
if(!singleObj){
singleObj = new fn(obj);
}
return singleObj;
}
}
var CreatePopbox = function(opation){
this.html = opation.html;
this._init();
};
CreatePopbox.prototype._init = function(){
this.div = document.createElement('div');
this.div.innerHTML = this.html;
document.body.appendChild(this.div);
};
var singlePopbox = getSingle(CreatePopbox);
var a = new singlePopbox({html:"this is a"});
//建立一个新的单例
var CreateTipbox = function(opation){
this.div = document.createElement('div');
this.div.style.color = opation.color;
this.div.innerHTML = opation.html;
document.body.appendChild(this.div);
}
//运用getSingle治理
var singleTipbox = getSingle(CreateTipbox);
var b = new singleTipbox({html:"this is b",color:"#f00"});
原文链接:javascript设想形式--单例形式