首页 > 编程语言 > 详细

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

时间:2019-10-28 18:41:51      阅读:128      评论:0      收藏:0      [点我收藏+]

参考:https://www.cnblogs.com/yonglin/p/8059183.html

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

              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();

 

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

原文:https://www.cnblogs.com/han-guang-xue/p/11754126.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!