单例模式
保证一个类仅有一个实例,并提供一个访问它的全局访问点
function Minister(name){ //大臣
this.name = name;
}
Minister.prototype.say = function(){
console.log(this.name + ':大王,冤枉')
}
function Emperor(){ //皇帝
this.name = '大王';
this.id = Math.random();
this.say = function(){
console.log(this.name + this.id + ': out!');
}
}
Emperor.getInstance = (function(){
var instance = null;
return function(){
if(!instance){
instance = new Emperor(); //只有一个实例
}
return instance;
}
})();
var p1 = new Minister('张三');
var p2 = new Minister('李四');
var p3 = new Minister('王五');
var emperor = Emperor.getInstance();
p1.say();
p2.say();
p3.say();
JS特色的单例模式
var me = {}
惰性单例
var createLoginLayer = (function(){
var loginLayer = null;
return function(){
if (!loginLayer) {
var loginLayer = document.createElement('div');
loginLayer.id = 'loginLayer';
loginLayer.innerHTML = '登录窗口';
loginLayer.style.display = 'none';
document.body.appendChild(loginLayer);
}
return loginLayer;
}
})();