1. 程式人生 > >使用Function.prototype實現一個AOP

使用Function.prototype實現一個AOP

AOP應用比較廣泛,在如今最為火熱spring框架中,裡面就用到了DI(依賴注入)和AOP(面向切面程式設計),那麼js中可以通過什麼方法來是實現AOP呢

AOP的特點是什麼,為什麼要使用它呢?很簡單,它的主要思想是將一些與核心業務邏輯模組無關的功能分離開來,比如,我們經常會使用到日誌統計,安全控制,異常處理,為了在保證到主業務的純淨和程式的高內聚,我們通過將一些附加的功能模組"動態植入"到邏輯模組中

下面我向大家介紹一下如何通過Function.prototype來實現AOP程式設計

 
  1. //業務主模組

  2. var myFun = function(){

  3. console.log("執行業務邏輯");

  4. }

  5.  
  6. //業務主模組預處理

  7. Function.prototype.before = function(fn){

  8. var _this=this;

  9. return function(){

  10. fn.apply(this,arguments);

  11. return _this.apply(this,arguments)

  12. }

  13. }

  14.  
  15. //業務主模組後處理

  16.  
  17. Function.prototype.after = function(fn){

  18. var _this = this;

  19. return function(){

  20. var result = _this.apply(this, arguments);

  21. fn.apply(this,arguments)

  22. return result;

  23. }

  24. }

  25.  
  26. var fun = myFun.before(function(){

  27.  
  28. console.log("模組的預處理");

  29.  
  30. }).after(function(){

  31.  
  32. console.log("模組的後處理");

  33.  
  34. });

  35.  
  36. fun();

  37.  

 

程式碼分析:

//業務主模組
var myFun = function(){
    console.log("執行業務邏輯");
}

//業務主模組預處理
Function.prototype.before = function(fn){
    var _this=this;   //用於儲存呼叫before方法的例項物件,此處的this指向了myFun
    return function(){  //把對函式的預處理與函式一封裝在一個函式中,並返回,用於呼叫after函式.
        fn.apply(this,arguments);  //用於執行對模組的預處理函式fn
        return _this.apply(this,arguments)  //返回 myFun函式
    }

}

//業務主模組後處理

Function.prototype.after = function(fn){
    var _this = this;  //此處的this指向before函式返回的函式,並使用_this儲存下來(也就是上面藍色標記的函式程式碼)
    return function(){ //再次把before函式返回的函式與對函式的後處理封裝在一個函式中,並返回
        var result = _this.apply(this, arguments);  //執行before函式的返回函式,返回值就是(return                                                                                                                                _this.apply(this,arguments)返回的值)
        fn.apply(this,arguments)  //用於執行對模組的後處理函式fn

        return result;
    }
}

var fun =  myFun.before(function(){
    
    console.log("模組的預處理");

}).after(function(){

    console.log("模組的後處理");

}); // 

fun();

 

 

總結:

可能有點繞來繞去的,但是隻要仔細思考,你一定會體會到其中的巧妙之處,簡而言之,就是把一個對函式的預處理封裝在一個before函式中,並把預處理函式和原函式返回,作為一個函式來對after的呼叫(因為Function上的prototype方法,所有的函式都可以呼叫).