- 装饰器本身是一个函数
- 装饰器接收的参数是构造函数
- 装饰器通过 @ 符号来使用
- 装饰器是在类创建好之后去执行,对类做一些装饰(跟调用实例没关系)
构造器的简单实例
```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);
<a name="GERrm"></a>## 使用多个装饰器装饰器的执行顺序是从下往上,从右往左```typescriptfunction testDecorator1(constructor: any) {console.log("testDecorator1");}function testDecorator2(constructor: any) {console.log("testDecorator2");}@testDecorator1@testDecorator2class HttpClient {}let http = new HttpClient();// testDecorator2 testDecorator1
定义装饰器工厂
function testDecorator(flag: boolean) {if (flag) {return function (constructor: any) {constructor.prototype.getName = () => {console.log("zws");};};} else {return function (constructor: any) {};}}// 装饰器工厂:可传参@testDecorator(true)class HttpClient {}let http = new HttpClient();(http as any).getName();
