TS装饰器

120 阅读1分钟

TS装饰器@主要用于对class及其里面的method,property,accesor,function params进行扩展。这篇文章主要讲对method的扩展。

定义

装饰器由@xxx组成,它是一个函数。xxx是其函数名,当装饰器用于class的method时,它接收3个参数,被装饰对象target,方法名name,以及被装饰的Property Descriptor对象。

经典应用
//装饰器拓展日志记录
class Demo {
    public a = 1
    public name = 'Demo'

    @log
    public sayName() {
        console.log(this.name)
    }

    @log
    public sayHello(s: any) {
        console.log(s)
    }
}

function log(target: any, key: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value
    descriptor.value = function(...arg: any[]) {
        console.log(`调用方法${key},参数为: ${JSON.stringify(arg)}`)
        const result = originalMethod.apply(this, [...arg])
        console.log(`方法${key}返回:${JSON.stringify(result)}`)
        return result
    }
}

const demo = new Demo()
demo.sayHello('this demo')
demo.sayName()