定义
保证一个类,仅有一个实例,并提供一个访问它的全局访问点。
方法
方法一:此方法有弊端,Test.instance挂在全局,能修改,不符合开闭原则
function Test(name) {
if (typeof Test.instance == 'object') {
return Test.instance
}
this.name = name;
Test.instance = this;
}
var a = new Test('a')
var b = new Test('a')
console.log(a == b) // true
方法二:利用闭包思想,但是还是有弊端,new出来的对象,它的构造函数constructor并不是Test,如果要在原型prototype加方法的话,new出来的对象并不能调用
function Test(name) {
var instance = this;
this.name = name;
Test = function () {
return instance
}
}
var a = new Test('a')
var b = new Test('a')
console.log(a == b) //true
方法三:完美单例模式
var Test = (function(){
var instance = null;
return function(name){
if(instance){
return instance
}
this.name = name
instance = this
}
})()
var a = new Test('a')
var b = new Test('a')
console.log(a == b) //true
运用
说了这么多我们在事件中运用一下,在html创建一个按钮,让它无论点击多少次都只出现一个弹窗(只是一个比喻)
var creat = (function(text){
var div = null
return function(text){
if(div){
return div
}
div = document.createElement('div')
div.innerText = text;
div.style.display = 'none';
document.body.appendChild(div);
return div
}
})()
btn.onclick = function(){
var div = creat('我是谁,我在哪')
div.style.display = 'block'
}
其实上面这个方法看起来还是不够高级,下面我们写一个更高级的方法,并调用它
var single = function (fn) {
var res = null;
return function () {
if (!res) {
res = fn.apply(this, arguments)
}
return res
}
} //单例模式高级方法
var creat = function (text) {
var div = document.createElement('div')
div.innerText = text;
div.style.display = 'none';
document.body.appendChild(div);
return div
} // 创建弹窗
var fn = single(creat) //调用单例模式函数
btn.onclick = function () {
var div = fn('我是谁,我在哪')
div.style.display = 'block'
}