TypeScript装饰器

是一种特殊类型的声明,用来监视,修改或替换类定义,它能够被附加到类声明,方法,访问符,属性或参数上。使用"@"符号作为前缀。也是对原有代码外层包装一层处理逻辑,是一种非侵入式的改变。一般实现函数类似于柯里化函数,返回一个函数作为返回值。一共有类装饰器、访问器装饰器、属性装饰器、方法装饰器、参数装饰器这几种,但是没有有函数装饰器

一、类装饰器 不传递参数

/**
 * 一、类装饰器 不传递参数
 * @param target
 */
 
function testFn(target) {
  target.age = 18;
}
 
@testFn
export class TestCode {
  name = 'TectCode'
}
const code = new TestCode();
console.log(code .name, code .age); // TestCode 18
 
/**
 * 类装饰器 传递参数
 * @param age
 */
 
function testFn(age) {
  /**
 * target 类本身
   */
  return function (target) {
    target.age = age;
  }
}
 
@testFn(22)
export class TestCode {
  name = 'TectCode';
  age: number;
}
const code = new TestCode();
console.log(code .name, code .age);  // TestCode 22

二、 访问器装饰器 主要应用于get set 修改该成员属性

/**
 * 二 访问器装饰器  主要应用于get set 修改该成员属性
 * @param value
 */
 
function testFn(value) {
  /**
 * target 类本身
 * propertyKey 属性名称
 * descriptor 该属性的属性描述符
   */
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    descriptor.configurable = value;
  };
}
 
export class TestCode {
  name = 'TectCode';
  _age = 20;
  @testFn(false)
  get age() {
    return this._age;
  }
 
  @testFn(true)
  get ages() {
    return this._age;
  }
}

三、 属性装饰器 紧靠属性前面 用于对属性的处理

/**
 * 三 属性装饰器 紧靠属性前面 用于对属性的处理
 * @param value
 */
 
function testFn(value) {
  /**
 * 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象。
 * propertyKey 属性名称
   */
  return function (target: any, propertyKey: string) {
    if (delete target[propertyKey]) {
      Object.defineProperty(target, propertyKey, {
        get: () => {
 
        },
        set: () => {
 
        },
        enumerable: true,
        configurable: true
      });
    }
  };
}
 
export class TestCode {
  @testFn('Hello ')
  name = 'TectCode';
}

四、 方法装饰器 紧靠方法前面 用于对方法的替换、修改等处理

/**
 * 四 方法装饰器 紧靠方法前面 用于对方法的替换、修改等处理
 * @param value
 */
 
function testFn() {
  /**
 * 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象。
 * propertyKey 属性名称
   */
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
 
  };
}
 
export class TestCode {
  @testFn
  name() {
    return 'TestCode'
  };
}

五、 参数装饰器 紧靠参数前面 用于监视参数是否被传入

/**
 * 五 参数装饰器 紧靠参数前面 用于监视参数是否被传入
 */
 
function testFn() {
  /**
   * 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象。
   * propertyKey 属性名称
   * 参数在函数参数列表中的索引
   */
  return function (target: any, propertyKey: string, parameterIndex: number) {
 
  };
}
 
export class TestCode {
  name( @testFn _name) {
    return 'TestCode'
  };
}

你可能感兴趣的:(#,TypeScript)