js设计模式-装饰者模式

123 阅读1分钟
定义

在不改变对象自身的基础上,在程序运行期间给对象动态的添加职责。这种动态添加职责的方式称为装饰者模式。

传统的装饰者模式
  const _getId = document.getElementById;
  document.getElementById = function(id) {
    alert(1)
    return _getId(id)
  }
  const button = document.getElementById('button')
  console.log(button)

但是这种方式存在以下问题:

  • 必须维护_a这个中间变量
  • this指向问题,尖头函数或者传统的function函数都会改变_a的this指向,所以这个函数内部如果需要使用this引用的话,都可能发生错误
用AOP装饰函数

把请求分别转发给新添加的函数和原函数,且负责保证它们的执行顺序,让新添加的函数在原函数之前执行(前置装饰),这样就实现了动态装饰的效果。

  Function.prototype.before = function(beforefn) {
    const _self = this;
    return function() {
      beforefn.apply(this, arguments)
      return _self.apply(this, arguments)
    }
  }
  Function.prototype.after = function(afterfn) {
    const _self = this;
    return function() {
      const ret = _self.apply(this, arguments);
      afterfn.apply(this, arguments)
      return ret
    }
  }
  document.getElementById = document.getElementById.before(function(){
    alert(1)
  })
  const button = document.getElementById('button')
  console.log(button)