属性装饰器

属性装饰器使用类的属性。

  1. function Override(label: string) {
  2. return function (target: any, key: string) {
  3. Object.defineProperty(target, key, {
  4. configurable: false,
  5. get: () => label
  6. });
  7. }
  8. }
  9. class Test {
  10. @Override('test') // invokes Override, which returns the decorator
  11. name: string = 'pat';
  12. }
  13. let t = new Test();
  14. console.log(t.name); // 'test'

以上示例必须使用--experimentalDecorators--emitDecoratorMetadata标志编译。

在这种情况下,装饰属性由传递给装饰器的标签替换。 重要的是注意属性值不能由装饰器直接操纵; 而是使用访问器。

这里是一个使用普通装饰器的经典属性示例。

  1. function ReadOnly(target: any, key: string) {
  2. Object.defineProperty(target, key, { writable: false });
  3. }
  4. class Test {
  5. @ReadOnly // notice there are no `()`
  6. name: string;
  7. }
  8. const t = new Test();
  9. t.name = 'jan';
  10. console.log(t.name); // 'undefined'

在这种情况下,name属性不可写,并且保持未定义。