思想
这么看来在全局环境下
var a = {};
这种形式就知足以上两条,可是全局变量不是单例模式
代理实现单例模式
var createPop = function (html) {
this.html = html;
this.createDom();
}
// 原型上挂载共享属性和共享的方法
createPop.prototype.createDom = function () {
var pop = document.createElement('div');
pop.innnerHTML = this.html;
document.body.appendChild(pop);
}
var createSingle = (function () {
var instance;
return function (html) {
if(!instance) {
instance = new createPop(html);
}
return instance;
}
})()
var pop0 = new createSingle('pop0'); // 这里new的是createSingle里面的返回的匿名函数,返回的引用类型的数据(注意)
var pop1 = new createSingle('pop1');
pop0 === pop1 // true
惰性单例,顾名思义就是在咱们须要的时候在去建立这个单例
- 将建立对象和管理单例的逻辑分离开来,仍是就上面的例子
// 业务逻辑
var createDom = function () {
var pop = document.createElement('div');
pop.innnerHTML = this.html;
document.body.appendChild(pop);
this.name = '测试'
return true;
}
// 保证只有一个实例
var createSingle = (function () {
var instace;
return function (fn) {
console.log(this); // 这个匿名被谁掉用,就指向谁,能够将createDom中的一些属性绑定到调用的对象上
// 这里就将createDom的name属性挂载到window上
return instace|| (instace = fn.call(this, arguments))
}
})()
createSingle(createDom);