装饰器模式
小于 1 分钟约 174 字
- 装饰器模式能够很好的对已有功能进行拓展,这样不会更改原有的代码,对其他的业务产生影响,这方便我们再较少的改动下对软件功能进行拓展
Function.prototype.before = function (beforeFn) {
var _this = this
return function () {
// 先进行前置函数调用
beforeFn.apply(this, arguments)
// 再执行原函数
return _this.apply(this, arguments)
}
}
Function.prototype.after = function (afterFn) {
var _this = this
return function () {
// 先执行原函数
var result = _this.apply(this, arguments)
// 再执行后置函数
afterFn.apply(this, arguments)
return result
}
}
function test() {
console.log('111111')
}
var test1 = test
.before(function () {
console.log('000000')
})
.after(function () {
console.log('222222')
})
test1()
// 000000
// 111111
// 222222