AOP编程

36 阅读1分钟

定义

AOP编程思想,即面向切面编程,是一种软件开发中的编程范式,旨在通过横切关注点的方式来解耦系统中的各个模块,这些横切点是指那些不属于业务逻辑本身,但会影响多个模块的代码,例如日志记录,埋点,性能上报等内容

代码实现

题目如下,test函数要实现console的具体内容前后加上====和++++,那我们用切面编程的设计思想实现以下

function test(){
    console.log('================')
    console.log(1)
    console.log('++++++++++++++++')
}
  1. 实现方式1,函数原型上挂载before,after的方式

调用方式及具体实现

Function.prototype.before = function(beforeFn){
    var _this = this
    return function(){
        beforeFn.apply(this, arguments)
        _this.apply(this, arguments)
    }
}
Function.prototype.after = function(afterFn){
    var _this = this
    return function(){
        _this.apply(this, arguments)
        afterFn.apply(this, arguments)
    }
}
function test(){
    console.log(1)
}
var obj = {
    test: test
}
test = obj.test
.before(function(){
    console.log('================')
}).after(function(){
    console.log('++++++++++++++++')
})
// 简单调用
test()
// 指定this和有参数传递的调用
test.call(obj,1,2,3)
  1. 函数劫持
function test(){
    console.log(1)
}
function log(fn){
    return function(){
        console.log('================')
        fn.apply(this,arguments)
        console.log('++++++++++++++++')
    }
}
const runTestWithLog = log(test)
runTestWithLog()
  1. 代理的方式
// 定义一个对象
let user = {
    name: 'John',
    sayHello: function(){
        console.log("hello", this.name)
    }
}
// 定义代理对象
let proxy = new Proxy(user,{
    get: function(target, property, receiver){
        console.log('================')
        let result = Reflect.get(target, property, receiver)
        console.log('++++++++++++++++')
        return result
    }
})