首页 > 解决方案 > 为什么实例属性的装饰器在静态属性的装饰器之前执行?

问题描述

我是 TypeScript 的新手。我很好奇为什么实例属性上的装饰器在静态属性上的装饰器之前执行?

这背后有什么原因吗?

考虑下面的代码:

function LogProp(target: any, propertyName: string | Symbol) {
  console.log(`Prop Decorator: ${propertyName} is logged`);
}

function LogMethod(
  target: any,
  name: string | Symbol,
  descriptor: PropertyDescriptor
) {
  console.log(`Method Decorator: ${name} is logged`);
}

class Book {
  @LogProp
  static staticProp: string;
  @LogProp
  instanceProp: string;

  constructor(val: string) {
    this.instanceProp = val;
  }

  @LogMethod
  instanceMethod() {
    return this.instanceProp;
  }

  @LogMethod
  static staticMethod() {
    return Math.random();
  }
}

游乐场链接

输出是:

Prop Decorator: instanceProp is logged
Method Decorator: instanceMethod is logged
Prop Decorator: staticProp is logged
Method Decorator: staticMethod is logged

为什么?

标签: typescripttypescript-decorator

解决方案


推荐阅读