首先简单的了解单例这个词语
单 :是单个的
例:是实例, 既然是实例那一定和 new的过程有关
在new 的过程中我们都是会生成一个 空的对象,开辟一个空间, 如果一个构造函数被new多次的话
那是不是要开辟多个空间,生成多个对象。
单例模式就是解决这个问题的,只生成一个对象来解决这个问题
下面这段代码体现了 每一次 new 都会生成不一样的实例,不一样的对象
function Fn() {
}
let a1 = new Fn()
let a2 = new Fn()
console.log(a1 == a2); // fasle
我们要实现的是 怎么让 a1 == a2 是 true ?
有没有一种可能第二次 new 的时候 和一次使用的是同一个空间呢!
我们修改一下代码
分析一下为什么是 true
a1 第一次 new 的时候 _instance = null
this 指向的 是 a1
全局的 _instance = this
第二次 new 的时候 由于 _instance 不等于 null 直接返回的 this 就是指向 a1 的this
所以 是 true
let _instance = null
function Fn() {
if(!_instance) {
_instance = this
}
return _instance
}
let a1 = new Fn()
let a2 = new Fn()
console.log(a1 == a2); // true
最后优化一下代码
使用闭包是为了防止全局变量等污染
这个 自执行函数的 window 是可以不传递的 , 如果不传递的话,会销毁性能
因为 会一层层的去找 window.Fn
(function(window) {
let _instance = null
function Fn() {
if(!_instance) {
_instance = this
}
return _instance
}
window.Fn = Fn
})(window)
let g1 = new Fn()
let g2 = new Fn()
console.log(g1 == g2); // true