当前位置:优学网  >  在线题库

Setter/Getter未在属性的第二个decorator上运行

发表时间:2022-07-04 00:16:20 阅读:92

我有两个装饰器,当我将它们附加到属性时,只有第一个定义的装饰器执行其setter/getter属性.内部函数本身运行Init Decorator 1Init Decorator 2.是什么导致第二个装饰器不执行setter/getter

以下是我如何定义我的两个装饰器:

export function Decorator1(): any {
  return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
    descriptor = descriptor || {};
    console.log('Init Decorator 1');
    descriptor.get = function (this: any) { console.log('Get Decorator 1'); }
    descriptor.set = function (this: any) { console.log('Set Decorator 1'); }
    return descriptor;
  }
}
export function Decorator2(): any {
  return (target: any, propertyKey: string, descriptor: PropertyDescriptor) => {
    descriptor = descriptor || {};
    console.log('Init Decorator 2');
    descriptor.get = function (this: any) { console.log('Get Decorator 2'); }
    descriptor.set = function (this: any) { console.log('Set Decorator 2'); }
    return descriptor;
  }
}

然后,我使用以下装饰器:

export class Test {
  @Decorator1()
  @Decorator2()
  code = '';

  constructor() {
    setTimeout(() => this.code = '123', 2000);
  }
}

new Test();

操场示例

结果

🎖️ 优质答案
相关问题