JavaScript设计模式之装饰器模式

装饰器模式比继承更轻便,不改变原有对象的方法,在原有方法的前面或者后面添加一些点缀功能。

  1. ES6写法
  • 装饰class
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()
  1. typescript写法
  • 装饰class
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()
  • 装饰class的属性
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()

你可能感兴趣的:(JavaScript设计模式,javascript,设计模式,装饰器模式)