关于typescript:使用-TypeScript-自定义装饰器给类的方法增添监听器-Listener

3次阅读

共计 906 个字符,预计需要花费 3 分钟才能阅读完成。

办法装璜器

语法

type MethodDecorator = <T>(
  target: Object,
  propertyKey: string | symbol,
  descriptor: TypedPropertyDescriptor<T>
) => TypedPropertyDescriptor<T> | void;

(1)target: 对于动态成员来说是类的结构器,对于实例成员来说是类的原型链。
(2)propertyKey: 属性的名称。
(3)descriptor: 属性的形容器。

办法装璜器不同于属性装璜器的中央在于 descriptor 参数。通过这个参数咱们能够批改办法本来的实现,增加一些共用逻辑。例如咱们能够给一些办法增加打印输出与输入的能力:

function logger(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
  const original = descriptor.value;

  descriptor.value = function (...args) {console.log('params:', ...args);
    const result = original.call(this, ...args);
    console.log('result:', result);
    return result;
  }
}

class C {
  @logger
  add(x: number, y:number) {return x + y;}
}

const c = new C();
c.add(1, 2);
// -> params: 1, 2
// -> result: 3

下面的例子,很像 Java 里的 AOP – Aspect Oriented Programming, 面向切片编程。

运行时,咱们装璜器施加的 target:

key 是被润饰的 add 办法的字符串名称:

descriptor 的 value 属性指向了 add 办法的原始实现:

…arg 代表任意数量的参数:

第 57 行的 Object.defineProperty, 将类的 add 办法批改成蕴含了 log 性能的新版本:

这样,稍后咱们调用 add 办法时,这个新版本就得以执行了:

更多 Jerry 的原创文章,尽在:” 汪子熙 ”:

正文完
 0