20.TS装饰器Decorator

109 阅读1分钟

装饰器

// 1.定义一个类的装饰器
const watcher: ClassDecorator = (target: Function) => {
  target.prototype.getName = <T>(name: T): T => {
    return name
  }
}
// 通过@watcher就能让A类实现这个函数
@watcher 
class A {}
// 通过@watcher就能让B类也实现这个函数
@watcher
class B {}
const a = new A();
(a as any).getName('Yang')
​
// 2.通过高阶函数可以实现 传递参数
const hello = (age: number): ClassDecorator => {
  return (target: Function) => {
    target.prototype.getAge = () => {
      return age
    }
  }
}
@hello(23)
class C {}
const c = new C()
// console.log((c as any).getAge()) // 23// 3.组合式装饰器
@watcher
@hello(23)
class D {}
​
const d = new D()
// console.log((d as any).getName('Yang')) // Yang
// console.log((d as any).getAge()) // 23// 4.属性装饰器
const flag: PropertyDecorator = (...args) => {
  console.log(args)
}
​
class E {
  @flag
  name: string
  constructor(name: string) {
    this.name = name
  }
}
​
let e = new E('Yang')
​
// 方法装饰器 及 参数装饰器 一样的