高阶函数实现AOP

  AOP(面向切面编程)的主要作用是把一些跟核心业务逻辑模块无关的功能抽离出来,这些跟逻辑无关的功能通常包括日志统计、安全控制、异常处理等。把这些功能抽离出来后,在通过"动态织入"的方式渗入业务逻辑模块中。这样做的好处是可以保持业务逻辑模块的纯净和高内聚性,其次是可以很方便的复用日志统计等功能模块。

  通过,在JavaScript中实现AOP,都是把一个函数'动态织入'到另一个函数之中,具体的实现技术有很多,本次通过扩展Function.prototype来做到这一点。代码如下:

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

 

posted @ 2017-03-28 13:38  zero7酱紫  阅读(167)  评论(0编辑  收藏  举报