nest装饰器

90 阅读1分钟

一、类装饰器 image.png

//一、类装饰器
const doc: ClassDecorator = (target: any) => {
  console.log('target', target)
  // 不破坏原有的类进行属性添加
  target.prototype.name = 'lihk'
}
@doc
class Lihk {
  constructor() {}
}

const lihk:any = new Lihk()
console.log('lihk.name', lihk.name)

二、属性装饰器

image.png

// 2.属性装饰器
const doc: PropertyDecorator = (target: any, key: string | symbol) => {
  //target指向lihk这个类的原型
  console.log('target', target,key)//{} name
}

class Lihk {
  @doc
  public name:string
  constructor() {
    this.name = 'lihk'
  }
}

三、方法装饰器 image.png

// 3.方法装饰器
const doc: MethodDecorator = (
  target: any,
  key: string | symbol,
  descriptor: any
) => {
  //这个类的描述,可写,不可枚举,可配置
  console.log('target', target, key, descriptor) 
  /* {} getName {
    value: [Function: getName],
    writable: true,
    enumerable: false,
    configurable: true
  } */
}

class Lihk {
  public name: string
  constructor() {
    this.name = 'lihk'
  }
  @doc
  getName() {}
}

四、参数装饰器

image.png

// 4.方法装饰器
const doc: ParameterDecorator = (
  target: any,
  key: string | symbol,
  index: number
) => {
  //参数所在的索引
  console.log('target', target, key, index) 
  /* {} getName 1 */
}

class Lihk {
  public name: string
  constructor() {
    this.name = 'lihk'
  }
  getName(age:number,@doc sex:string) {}
}