设计模式篇之单例模式
普通单例模式
let instance=null;
function Demo(){
if(instance){
return instance;
}
instance=this;
}
let a=new Demo();
let b=new Demo();
console.log(a===b);指向同一个实例,同一片内存地址
虽然上述例子的确实现了单例模式,但是instance暴露在了外面,外界可以访问到并且修改,引起不必要的问题!
就绪函数+单例模式
(function(e){
let instance=null;//屏蔽了instance,使外界不可访问
function Demo(){
if(instance){
return instance;
}
instance=this;
}
e.Demo=Demo;//将构造函数挂载到Window上,供外界访问.
})(window);
let a=new Demo();
let b=new Demo();
console.log(a===b);
这里是引用
闭包-惰性函数-单例模式
function Demo(){
var instance=this;
Demo=function(){ //惰性函数(只执行一次,后面直接调用)
return instance;
}
}
let a=new Demo();
let b=new Demo();
console.log(a===b);
但是还是会有个问题,接下来我们来探讨下哈!
以上将Demo.prototype.mydemo=“asdasdasd”;
放在let a=new Demo();
let b=new Demo();之前,是没问题的,因为a、b实例的constructor都是指向最外层的Demo()
因为Demo.prototype.mydemo=“asdasdasd”;放在中间的话在new第一个Demo实例时,已经把惰性函数赋值给了Demo
所以constructor就改变了。而从始至终返回的还是最外层的Demo实例,
自然就为undefined了,接下来咱们就进一步进行改善吧!
好啦~今天就分享到这里啦!把Demo()原型挂载到惰性函数Demo()原型上就完事啦~