装饰器(Decorator)

在 ECMAScript 的一项提案中,开始引入了装饰器语法,装饰器本质上是一个对类进行处理的函数。装饰器函数的第一个参数,就是要修饰的目标类。装饰器能够被附加到类声明,方法, 访问符,属性或参数上。在 TypeScript 中启用装饰器模式需要在 tsconfig.json 中开启。

  1. {
  2. "compilerOptions": {
  3. "experimentalDecorators":true
  4. }
  5. }

我们来看一个装饰器的简单例子

类装饰器

当装饰器被用于 Class 的时候,装饰器接受1个参数,这个参数就是它要装饰的 Class。

function myClassDecorator(clazz: typeof MyClass) {
    clazz.c = 'c'
    return clazz
}

@myClassDecorator
class MyClass {
    a: number = 0;
    b: string = "hello";
    static c:string;
}

MyClass.c // c

方法装饰器

方法装饰器可以接收三个参数

  • target:对于静态成员来说是类的构造函数,对于实例成员是类的原型对象
  • propertyKey:成员的名字
  • descriptor:成员的属性描述符 ```typescript // enumerable 装饰器用于更改成员的可枚举性 function enumerable(value: boolean) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
      descriptor.enumerable = value;
    
    }; }

class MyClass { static a: number = 0; static b: string = “hello”; @enumerable(false) sayHi() { return “Hi, “ + this.b; } } ``` 更多关于装饰器的介绍,可以参照:https://www.typescriptlang.org/docs/handbook/decorators.html