外观模式
外观模式,顾名思义,外表看起来相同,但实际可能不一致。在JS中外观模式通常用于处理兼容性问题。比如封装了一个bindEvent
事件绑定方法,不同的浏览器会调用bindEvent
内部封装的浏览器所支持的方法。
外观模式封装示例
myEvent = {
stop: function (e) {
if (typeof e.preventDefault() === "function") {
return e.preventDefault();
}
if (typeof e.stopPropagation() === "function") {
return e.stopPropagation();
}
//for IE
if (typeof e.returnValue === "boolean") {
return (e.returnValue = false);
}
if (typeof e.cancelBubble === "boolean") {
return (e.cancelBubble = true);
}
},
bindEvent(dom, type, fn) {
if (dom.addEventListener) {
dom.addEventListener(type, fn, false);
} else if (dom.attachEvent) {
dom.attachEvent('on' + type, fn);
} else {
dom['on' + type] = fn;
}
}
}
myEvent.bindEvent(document.querySelector('button'),
'click', () => console.log('button clicked'))