装饰器模式比继承更轻便,不改变原有对象的方法,在原有方法的前面或者后面添加一些点缀功能。
const logWrapper = targetClass => {
const oldRender = targetClass.prototype.render
targetClass.prototype.render = () => {
console.log('before render')
oldRender.apply(this)
console.log('after render')
}
return targetClass
}
class App {
constructor(title) {
this.title = title
}
render() {
console.log(`渲染页面${this.title}`)
}
}
App = logWrapper(App)
new App().render()
const logWrapper = targetClass => {
const oldRender = targetClass.prototype.render
targetClass.prototype.render = () => {
console.log('before render')
oldRender.apply(this)
console.log('after render')
}
return targetClass
}
@logWrapper
class App {
constructor(title) {
this.title = title
}
render() {
console.log(`渲染页面${this.title}`)
}
}
new App().render()
const logWrapper = (target, name, descriptor) => {
console.log(arguments)
let originRender = descriptor.value
descriptor.value = function () {
console.log('before render')
originRender.bind(this)()
console.log('after render')
}
console.log(target)
}
class App {
constructor() {
this.title = '饥人谷首页'
}
@logWrapper
render() {
console.log('渲染页面:' + this.title);
}
}
new App().render()