TS系列教程十四:装饰器

49 阅读1分钟

装饰器的概念

装饰器是在不修改原函数或类的基础上扩展类的属性或方法

function simpleDecorator(
    target: any,
) {
    console.log('hi, this is ' + target);
    target.version  = 'A';
    return target;
}
@simpleDecorator;
class Person{}

当代码执行到Person时 会自动调用simpleDecorator方法,基本格式为:@+函数名

function simpleDecorator(
    target: any,
) {
    // console.log('hi, this is ' + target);
    target.version  = 'A';
    return target;
}
function sayHi1(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    console.log('hi, this is ' + target,propertyKey,descriptor);
}
@simpleDecorator
class A {
    #name: string;
    constructor(name: string) {
        this.#name = name;
    }
    @sayHi1
    sayHi() {
        console.log('Hi, my name is ' + this.#name);
    }
}
new A('Alice').sayHi(); 

在执行sayHi之前先执行sayHi1,传递三个参数this,函数名,函数体。不熟悉js装饰器的小伙伴可以先去熟悉下。