JavaScript AOP

90 阅读1分钟
    Function.prototype.before = function(beforeFn){
        let self = this
        return function(){
            beforeFn.apply(this,arguments)
            self.apply(this, arguments)
        }
    }
    
    Function.prototype.after = function(afterFn){
        let self = this
        return function(){
            let ret = self.apply(this,arguments)
            afterFn.apply(this,arguments)
            return ret
        }
    }
    
    let func = function(){ console.log(2)}
    
    func = func.before(function(){console.log(1)}).after(function(){console.log(3)})
    
    func()

打印

1
2
3