美文网首页
js 设计模式 - 装饰模式

js 设计模式 - 装饰模式

作者: 康乐芳华 | 来源:发表于2019-04-02 18:13 被阅读0次

    存在两个函数

    function apple(str) { //  a
      console.log('apple');
    };
    function banana(str) {  //  b
      console.log('banana');
    };
    

    在不改动源代码的情况下实现 applebanana 先执行, 不考虑计时器

    Function.prototype.before_ = function(beforeFn) {  //  c
      const self = this;
      return function() {  //  d
        beforeFn.apply(this, arguments);
        return self.apply(this, arguments);  
      }
    };
    apple.before_(banana)(); 
    
    //  a 表示函数; -> 表示执行; a() 表示函数执行了 
    // --------------------------------------------
    //  a.c(b)  -> d
    //  d()  -> ( b() && a() )
    

    函数 before_ 返回了一个代理函数, 该代理函数里面的两行代码的顺序反映了原两函数的需要执行顺序,
    返回的代理函数的第一行是最先执行的函数
    也有 applebanana 后执行的版本

    Function.prototype.after_ = function(afterFn) {
      const self = this;
      return function() {
        const res = self.apply(this, arguments);
        afterFn.apply(this, arguments);
        return res;
      }
    };
    apple.after_(banana)(); 
    

    相关文章

      网友评论

          本文标题:js 设计模式 - 装饰模式

          本文链接:https://www.haomeiwen.com/subject/exdgbqtx.html