Skip to content

Latest commit

 

History

History
33 lines (29 loc) · 975 Bytes

File metadata and controls

33 lines (29 loc) · 975 Bytes

博文

装饰者模式

在原型不变的基础是,通过对他进行包装,附加属性,附加方法,使原有的对象、函数能满足更复杂的需求。因为已经说了装饰,所以只是添加新功能时候可以用。 装饰者模式中可以不了解原有功能,并且原有的方法照样可以原封不动的使用,如果原有的方法不能用了,说明你的模式有问题,是不可取的。

let btn = document.querySelector('input')
btn.onclick = () => {
  alert(1)
}
// 装饰者
const decorator = (dom, fn) => {
  if (typeof dom.onclick === 'function') {
    let oldFn = dom.onclick
    dom.onclick = () => {
      oldFn()
      fn()
    }
  } else {
    dom.onclick = fn
  }
}
// 利用装饰者对元素附加事件
decorator(btn, () => {
  setTimeout(() => {
    alert('bye')
  }, 1000)
})