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();
相關文章
相關標籤/搜索