JS实现AOP 面向切面编程 (装饰者模式)

2,803 阅读1分钟

1、什么是AOP

AOP(Aspect-oriented programming)是面向切面的编程。可以在不修改原有代码的情况下增加新功能。

2、例如:

Function.prototype.before = function (fn) {  
    let that = this;  
    return function () { // => 当前返回的函数就是newFn    
        fn.apply(that,arguments); // {0:123,1:456}    
        that.apply(that, arguments);  
    }
}
let fn = function (val) {  
    console.log('old~~~~',val);
}
let newFn = fn.before(function(){  
    console.log('new~~~');
});
newFn('123');