方法装饰器

  • 普通方法,target 对应的是类的 prototype;
  • 静态方法,target 对应的是类的构造函数
  • key 对应的是方法名; descriptor 可以操控属性描述符( prototype descriptor )对象
  • 方法装饰器也是等类创建好之后就会立即执行 ```typescript function getNameDecorator(target: any,key: string,descriptor: PropertyDescriptor) { // 方法将不能重写 descriptor.writable = false; // 返回值变为 descriptor descriptor.value = () => { return “descriptor”; }; console.log(target, key); } class Test { name: string; constructor(name: string) { this.name = name; } @getNameDecorator getName() { return this.name; } }

let test = new Test(“zws”); console.log(test.getName()); // descriptor

  1. <a name="tNKH3"></a>
  2. ## 访问器装饰器
  3. - 访问器装饰器跟方法装饰器接收的参数一样
  4. ```typescript
  5. function visitDecorator(
  6. target: any,
  7. key: string,
  8. descriptor: PropertyDescriptor
  9. ) {
  10. console.log(key);
  11. }
  12. class Test {
  13. private _name: string;
  14. constructor(name: string) {
  15. this._name = name;
  16. }
  17. get name() {
  18. return this._name;
  19. }
  20. @visitDecorator
  21. set name(name: string) {
  22. this._name = name;
  23. }
  24. }
  25. let test = new Test("zws");
  26. test.name = "zws";
  27. console.log(test.name);

属性装饰器

  • 接收两个参数:target(test 对应的prototype),key(属性名)
  • 修改的是并不是实例上的 name,而是原型上的 name ```typescript function nameDecorator(target: any, key: string): any { target[key] = “zbl”; }

class Test { @nameDecorator name = “zws”; }

let test = new Test(); console.log(test.name, (test as any).proto.name);

  1. <a name="9uIhd"></a>
  2. ## 参数装饰器
  3. - 接收三个参数:原型、方法名、参数所在位置
  4. ```typescript
  5. function paramDecorator(target: any, key: string, parameIndex: number): any {
  6. console.log(target, key, parameIndex);
  7. }
  8. class Test {
  9. getInfo(@paramDecorator name: string, age: number) {
  10. console.log(`姓名:${name};年龄:${age}`);
  11. }
  12. }
  13. let test = new Test();
  14. test.getInfo("zws", 13);