TypeScript 类装饰器的一个例子和使用单步调试搞清楚其运行原理

官方文档

类装饰器的定义如下:

type ClassDecorator = <TFunction extends Function>
  (target: TFunction) => TFunction | void;

接收一个函数,返回一个新的函数。类装饰器本身也是一个函数。

输入参数 target:类的构造器。

返回参数:如果类装饰器返回了一个值,她将会被用来代替原有的类构造器的声明。

因此,类装饰器适合用于继承一个现有类并添加一些属性和方法。
看一个例子:

type Consturctor = { new (...args: any[]): any };

function toString<T extends Consturctor>(BaseClass: T) {
  return class extends BaseClass {
    toString() {
      return JSON.stringify(this);
    }
  };
}

@toString
class C {
  public foo = "foo";
  public num = 24;
}

console.log(new C().toString())
// -> {"foo":"foo","num":24}

运行时调试入口:main.js

main.js 里加载应用开发的 AppModule,作为 bootstrapModule:

AppModule 里启动 AppComponent:

整个 class C 的定义,作为 toString 的输入参数:

在 Angular library tslib.es6.js里的 __decorate 方法,能看到我们自己定义的装饰器 toString:

被装饰器修饰的目标类 class C:

装饰器返回一个新的子类,扩展自基类,并且覆盖了 toString 方法:

这个 tslib.es6.js, 在本地的 node_modules 文件夹里也能找到:

TypeScript decorator 没有什么魔术,还是调用的 Object.defineProperty 这个原生方法:

调用之前:

调用之后,JSON 实现的 toString 方法出现在其原型链上:

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

原文地址:https://www.cnblogs.com/sap-jerry/p/14958465.html