使用Function.prototype實現一個AOP
AOP應用比較廣泛,在如今最為火熱spring框架中,裡面就用到了DI(依賴注入)和AOP(面向切面程式設計),那麼js中可以通過什麼方法來是實現AOP呢
AOP的特點是什麼,為什麼要使用它呢?很簡單,它的主要思想是將一些與核心業務邏輯模組無關的功能分離開來,比如,我們經常會使用到日誌統計,安全控制,異常處理,為了在保證到主業務的純淨和程式的高內聚,我們通過將一些附加的功能模組"動態植入"到邏輯模組中
下面我向大家介紹一下如何通過Function.prototype來實現AOP程式設計
-
//業務主模組
-
var myFun = function(){
-
console.log("執行業務邏輯");
-
}
-
//業務主模組預處理
-
Function.prototype.before = function(fn){
-
var _this=this;
-
return function(){
-
fn.apply(this,arguments);
-
return _this.apply(this,arguments)
-
}
-
}
-
//業務主模組後處理
-
Function.prototype.after = function(fn){
-
var _this = this;
-
return function(){
-
var result = _this.apply(this, arguments);
-
fn.apply(this,arguments)
-
return result;
-
}
-
}
-
var fun = myFun.before(function(){
-
console.log("模組的預處理");
-
}).after(function(){
-
console.log("模組的後處理");
-
});
-
fun();
程式碼分析:
//業務主模組
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方法,所有的函式都可以呼叫).