上一小节在一个类上面加了一个类装饰器,其实类装饰器的本质就是一个语法糖。上一小节的代码如下:
// 定义一个装饰器const moveDecorator: ClassDecorator = (target: Function)=> {// target 表示使用装饰器的类target.prototype.getPosition = (): {x: number; y: number}=> {return {x: 100, y: 100}}}@moveDecoratorclass Tank {// [x: string]: any; // ??? 索引签名public getPosition() {}}const t = new Tank();console.log(t.getPosition());
给一个类添加一个装饰器 通过 @装饰器名的形式来添加。上面代码其实相当于下面这种写法:
// 定义一个装饰器
const moveDecorator: ClassDecorator = (target: Function)=> {
// target 表示使用装饰器的类
target.prototype.getPosition = (): {x: number; y: number}=> {
return {x: 100, y: 100}
}
}
// @moveDecorator
class Tank {
// [x: string]: any; // ??? 索引签名
public getPosition() {}
}
const t = new Tank();
moveDecorator(Tank); // 调用装饰器方法,并且把类传入进去
console.log(t.getPosition());
