javascript singleton 單例模式 closure 閉包
阿新 • • 發佈:2018-12-18
* 抽象的單例函式 (通過closure 閉包實現)
var singleton = function(fn) {
var result;
return function() {
return result || (result = fn.apply(this, arguments));
}
};
* 建立一個唯一的 modal 遮罩層
function Modal(opacity) { this.opacity = opacity || 0.2; var div = document.createElement("div"); div.style.opacity = this.opacity; div.style.position = "absolute"; div.style.left = 0; div.style.top = 0; div.style.width = document.body.clientWidth + "px"; div.style.height = document.body.clientHeight + "px"; div.style.backgroundColor = "black"; div.style.zIndex = 9; document.body.appendChild(div); } Modal.getInstance = singleton(function(op) { return new Modal(op); });
* test
var modal1 = Modal.getInstance(0.3); var modal2 = Modal.getInstance(0.4); console.log(modal1 === modal2); // true console.log(modal1); // Modal {opacity: 0.3} console.log(modal2); // Modal {opacity: 0.3} var modal3 = Modal.getInstance(0.5); console.log(modal3); // Modal {opacity: 0.3}