前端面向切面编程(APO)

488 阅读1分钟

APO(面向切面编程)的主要作用是把一些跟核心业务代码无关的功能抽离出来,其实就是给原函数加一层。不用管原函数 内部实现 (vue2.0 都是这么用的,开启事务和关闭事务)

在 java 中分为静态和动态APO,静态主要是 通过继承的方式(用好多次就需要写好多次)。Spring 封装了APO有很好的封装,有动态 APO。

function perform(anymethod, wrapper) {
    wrapper.forEach(item => item.initfn())
    anymethod()
    wrapper.forEach(item => item.endfn())
}

perform(function(){
    console.log('anymethod')
},[
    {
        initfn:function(){
            console.log('initfn1')
        },
        endfn:function(){
            console.log('endfn1')
        }
    },
    {
        initfn:function(){
            console.log('initfn2')
        },
        endfn:function(){
            console.log('endfn2')
        }
    }
])
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');