JS达成前置和主摄AOP

原创
小哥 3年前 (2022-11-14) 阅读数 39 #大杂烩
Function.prototype.before = function (beforefn) {
    var _self = this; //保存原始函数引用 例如,这里的要点是func
    return function () { //返回包含原始函数和新函数的。"代理函数"
     beforefn.apply(_self, arguments); //执行新功能,正确this 原来this指向的是window
     //执行原始功能
    return _self.apply(_self, arguments); // 使用arguments传参, 使用apply打电话很方便
    }
   };
   Function.prototype.after = function (afterfn) {
    var _self = this;
    return function () {
     var ret = _self.apply(_self, arguments);
     afterfn.apply(_self, arguments);
     return ret;
    }
   };
   var func = function (...arguments) {
       console.log(2, arguments);
   }
   func = func.before(function (...arguments) {
    console.log("1", arguments);
   }).after(function (...arguments) {
    console.log("3", arguments);
   })

   func(1, 2, 3);


参考文章为 this指向,在防抖功能中fn.apply(this,arguments)作用

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除

热门