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

2次阅读

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

官网文档

类装璜器的定义如下:

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 的原创文章,尽在:” 汪子熙 ”:

正文完
 0