javascript singleton 单例模式 closure 闭包

* 抽象的单例函数 (通过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}

猜你喜欢

转载自blog.csdn.net/fareast_mzh/article/details/84324470