var singleton = (function() {
let obj = null
return function() {
if (obj) {
return obj
}
// TODO: init obj
init();
}
})()
主要应用场景
单例工厂
var singletonFactory = (function() {
let cache = null
return function(fn) {
if (cache) {
return cache
}
cache = new fn()
}
})()
function LoginLayer() {
var domObj = document.createElement('div')
document.body.appendChild(domObj)
domObj.style.display = 'none'
return domObj
}
var getLoginLayerSingleton = singletonFactory(LoginLayer)
btn1.onclick = function() {
// show
var loginLayer = getLoginLayerSingleton()
loginLayer.style.display = 'block'
}
btn1.onclick = function() {
// hidden
var loginLayer = getLoginLayerSingleton()
loginLayer.style.display = 'none'
}
网友评论