JavaScript实现相似java编程中AOP编程方法,动态顺序执行函数

参考:http://www.javashuo.com/article/p-xrxwlvxs-ky.htmlhtml

以前项目中一直有以下的写法,没有想明白then和catch函数是如何去相似AOP的方法去实现的,app

              ycxUploadFile(opts_image).then(res=>{
                console.log(res)
              }).catch(err=>{
                util.showTips('检查报告上传失败');
              })
            }
          

 

经过以上博主研究发现js中能够这样去实现代码,我的感受这样写好处很大,首先封装组件,公共的请求等有很大的优点,能够去掉不少冗余的代码函数

 

 

Function.prototype.before = function (beforefn) {
       var _self = this;    //保存原函数引用
       return function () { //返回包含了原函数和新函数的"代理函数"
           beforefn.apply(this, arguments); //执行新函数,修正this
           return _self.apply(this, arguments); //执行原函数
       }
   };

   Function.prototype.after = function (afterfn) {
       var _self = this;
       return function () {
           var ret = _self.apply(this, arguments);
           afterfn.apply(this, arguments);
           return ret;
       }
   };

   var func = function () {
       console.log("2")
   }

   func = func.before(function () {
       console.log("1");
   }).after(function () {
       console.log("3");
   } )

   func();
相关文章
相关标签/搜索