var Conf=(function(){ var conf={ MAX_NUM:100, MIN_NUM:1, COUNT:1000 } //返回取值器对象 return { get: function(name){ return conf[name]?conf[name]:null; } } })() var count=Conf.get('COUNT') console.log(count)//1000
惰性单例
在需要的时候才创建对象实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//惰性单例 let getSingle=function(fn){ let res; returnfunction(){ return res || (res = fn.apply(this,arguments)) } } let createLoginLayer = function(){ let div = document.getElementById('div') div.innerHTML = "我是登录浮窗" div.style.display='none' document.body.appendChild(div) return div } let createSingleLoginLayer = getSingle(createLoginLayer) document.getElementById('loginBtn').onclick = function(){ let loginLayer = createSingleLoginLayer() loginLayer.style.display='block' }