装饰者模式
装饰者模式也称为包装模式「Wrapper Pattern」:给对象动态的增加职责的方式称为装饰者模式,装饰者模式能够在不改变对象自身的基础上,在程序运行期间给对象动态地添加职责。跟继承相比,装饰者是一种更轻便灵活的做法,这是一种「即用即付」的方式,比如天冷了就多穿一件外套
模式动机
实现
const showLogin = function() {
log()
console.info('打开登录浮层')
}
const log = function() {
console.info('上报数据')
}
button.onclick = showLoginAOP 装饰函数
Function.prototype.before = function(beforefn) {
const __self = this // 保存原函数的引用
return function() {
beforefn.apply(this, arguments) // 执行新函数,且保证 this 不被劫持,新函数接受的参数也会被原封不动地传入原函数,新函数在原函数之前执行
return __self.apply(this, arguments) // 执行原函数并返回原函数的执行结果
}
}
Function.prototype.after = function(afterfn) {
const __self = this
return function() {
let ret = __self.apply(this, arguments)
afterfn.apply(this, arguments)
return ret
}
}小结
优点
缺点
Last updated
Was this helpful?