- 装饰器是一种特殊类型的声明,本质上就是一个方法,可以注入到类、方法、属性、参数上,扩展其功能;
- 常见的装饰器:类装饰器、属性装饰器、方法装饰器、参数装饰器…
- 装饰器在写法上有:普通装饰器(无法传参)、装饰器工厂(可传参)
- 装饰器已是ES7的标准特性之一
类装饰器
function hello(params: any) {console.log(params);// 就是World类,可以扩展属性及方法params.prototype.name = 'world'; // 添加属性params.prototype.tell = () => { // 添加方法console.log(`hello ${this.name}`);}}@helloclass World {// ...}const hw:any = new World();console.log(hw.name); // worldhw.tell() / hello world
上面的hello就被调用了, 它有什么用? 他可以动态扩展 World 类的属性和方法,在不修改类的前提下来扩展。
装饰器工厂
function color(value: string) { // 装饰器工厂 参数是传进来的参数return function (target) { // 装饰器 参数是类target.prototype.color = value;}}@color('red')class Cloth {// ...}const cloth:any = new Cloth();console.log(cloth.color); // red
重载构造函数
function color<T extends { new (...args: any[]): {} }>(constructor: T) {return class extends constructor {color = "red";newColor = "green";getColor() {console.log(this.newColor);}};}@colorclass Cloth {color: string;constructor() {this.color = "blue";}getColor() {console.log(this.color);}}const cloth: Cloth = new Cloth();cloth.getColor(); // redconsole.log(new Cloth()); // {color: red, newColor: green}
方法装饰器
function enumerable(value: boolean) {return function (target: any,propertyKey: string,descriptor: PropertyDescriptor) {descriptor.enumerable = value;console.log(target, propertyKey, descriptor);// 类, 方法名 属性描述符};}class Greeter {greeting: string;constructor(message: string) {this.greeting = message;}@enumerable(false)greet() {return "Hello, " + this.greeting;}}
当装饰器被执行时, greet的属性描述符的 enumerable 属性 就被设置成了 false。
访问器装饰器
function configurable(value: boolean) {return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {descriptor.configurable = value;};}class Point {private _x: number;private _y: number;constructor(x: number, y: number) {this._x = x;this._y = y;}@configurable(false)get x() { return this._x; }@configurable(false)get y() { return this._y; }}
成员的属性描述符,可配置项就被修改了。
