js设计模式

// 单列模式 // 定义:保证一个类仅有一个实例,并提供一个访问他的全局访问点 // 用代理模式实现单例 var CreateDiv = function(html) { this.html = html this.init() } CreateDiv.prototype.init = function() { var div = document.createElement('div') div.innerHTML = this.html document.body.appendChild(div) } // 引入单例代理类 var ProxySingletonCreateDiv = (function() { var instance return function(html) { if(!instance) { instance = new CreateDiv(html) } return instance } })() var x = new ProxySingletonCreateDiv('hello') var y = new ProxySingletonCreateDiv('world') var z = new CreateDiv('world') var u = new CreateDiv('xxxx')

// 惰性单例模式,在合适的时候才创建对象,创建单个登陆框,iframe等 var getSingle = function(fn) { var result return function() { return result || result = fn.apply(this, arguments) } }

var createLoginLayer = function() { var div = document.createElement('div') div.innerHTML = '我是登陆窗口' div.style.display = 'none' document.body.appendChild(div) return div }

var createSingleLoginLayer = getSingle(createLoginLayer)

document.getElementById('btn1').onclick = function() { alert(1) var loginLayer = createSingleLoginLayer() loginLayer.style.display = 'block'

}

JSRUN notes