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