Appearance
AOP作用: 把一些跟核心业务逻辑模块无关的功能抽离出来(如日志统计、安全控制、异常处理等), 再通过"动态植入"的方式嵌入业务逻辑模块中
js
Function.prototype.before = function (cb) {
let _this = this // func
return function (...args) {
cb.call(this, ...args) // 执行beforeCb, this是window
return _this.call(this, ...args) // 执行func
}
}
Function.prototype.after = function (cb) {
let _this = this // before返回的函数
return function (...args) {
let res = _this.call(this, ...args) // 执行before返回的函数, this是window
cb.call(this, ...args) // 最后执行afterCb
return res
}
}
const func = (...args) => {
console.log('func', args)
}
const beforeCb = (...args) => { // func执行之前会先执行before
console.log('before', args)
}
const afterCb = (...args) => {
console.log('after', args)
}
func
.before(beforeCb)
.after(afterCb)('a', 'b')