• 装饰器本身是一个函数
  • 装饰器接收的参数是构造函数
  • 装饰器通过 @ 符号来使用
  • 装饰器是在类创建好之后去执行,对类做一些装饰(跟调用实例没关系)

    构造器的简单实例

    ```typescript function testDecorator(constructor: any) { // 动态扩展的属性 constructor.prototype.apiUrl = “xxx”; // 动态扩展的方法 constructor.prototype.run = function () { console.log(“我是一个run方法”); }; }

// 使用类装饰器(普通装饰器,无法传参) @testDecorator class HttpClient {}

let http = new HttpClient(); console.log((http as any).apiUrl);

  1. <a name="GERrm"></a>
  2. ## 使用多个装饰器
  3. 装饰器的执行顺序是从下往上,从右往左
  4. ```typescript
  5. function testDecorator1(constructor: any) {
  6. console.log("testDecorator1");
  7. }
  8. function testDecorator2(constructor: any) {
  9. console.log("testDecorator2");
  10. }
  11. @testDecorator1
  12. @testDecorator2
  13. class HttpClient {}
  14. let http = new HttpClient();
  15. // testDecorator2 testDecorator1

定义装饰器工厂

  1. function testDecorator(flag: boolean) {
  2. if (flag) {
  3. return function (constructor: any) {
  4. constructor.prototype.getName = () => {
  5. console.log("zws");
  6. };
  7. };
  8. } else {
  9. return function (constructor: any) {};
  10. }
  11. }
  12. // 装饰器工厂:可传参
  13. @testDecorator(true)
  14. class HttpClient {}
  15. let http = new HttpClient();
  16. (http as any).getName();