时间: 2020-08-25|tag:28次围观|0 条评论

摘自《JavaScript设计模式与开发实践》

装饰者模式能够在不改变对象自身的基础上,在程序运行期间给对象动态地添加职责。跟继承相比,装饰者是一种更轻便灵活的做法,这是一种“即用即付”的方式,比如天冷了就多穿一件外套,需要飞行时就在头上插一支竹蜻蜓,遇到一堆食尸鬼时就点开 AOE(范围攻击)技能。

 const plane = {    fire: function () {      console.log('发射普通原子弹')    }  }  const missileDecorator = function () {    console.log('发射导弹')  }  const atomDecorator = function () {    console.log('发射原子弹')  }    const fire1 = plane.fire  plane.fire = function() {    fire1()    missileDecorator()  }    const fire2 = plane.fire  plane.fire = function() {    fire2()    atomDecorator()  }    plane.fire() // // 分别输出: 发射普通子弹、发射导弹、发射原子弹

用 AOP 装饰函数

<html><button id="button"></button><script>  const _getElementById = document.getElementById  document.getElementById = function() {    alert (1)    return _getElementById.apply( document, arguments )  }  const button = document.getElementById( 'button' )</script></html>
Function.prototype.before
<html>  <button id="button"></button><script>  Function.prototype.before = function( beforefn ){    const __self = this    return function(){      beforefn.apply( this, arguments )      return __self.apply( this, arguments )    }  }  document.getElementById = document.getElementById.before(function(){    alert (1)  })</script></html>
Function.prototype.after
  Function.prototype.after = function (afterfn) {    const _self = this    return function () {      var ret = _self.apply(this, arguments)      afterfn.apply(this, arguments)      return ret    }  }   window.onload = function(){    alert (1)  }  window.onload = ( window.onload || function(){} ).after(function(){    alert (2)  }).after(function(){    alert (3)  }).after(function(){    alert (4)  })

文章转载于:https://www.jianshu.com/p/97bc09b32a61

原著是一个有趣的人,若有侵权,请通知删除

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《装饰者模式
   

还没有人抢沙发呢~