上一小节在一个类上面加了一个类装饰器,其实类装饰器的本质就是一个语法糖。上一小节的代码如下:

    1. // 定义一个装饰器
    2. const moveDecorator: ClassDecorator = (target: Function)=> {
    3. // target 表示使用装饰器的类
    4. target.prototype.getPosition = (): {x: number; y: number}=> {
    5. return {x: 100, y: 100}
    6. }
    7. }
    8. @moveDecorator
    9. class Tank {
    10. // [x: string]: any; // ??? 索引签名
    11. public getPosition() {}
    12. }
    13. const t = new Tank();
    14. console.log(t.getPosition());

    给一个类添加一个装饰器 通过 @装饰器名的形式来添加。上面代码其实相当于下面这种写法:

     // 定义一个装饰器
      const moveDecorator: ClassDecorator = (target: Function)=> {
        // target 表示使用装饰器的类
        target.prototype.getPosition = (): {x: number; y: number}=> {
          return {x: 100, y: 100}
        }
      }
    
      // @moveDecorator
      class Tank {
        // [x: string]: any; // ??? 索引签名
        public getPosition() {}
      }
    
    
      const t = new Tank();
      moveDecorator(Tank); // 调用装饰器方法,并且把类传入进去
      console.log(t.getPosition());