本篇文章将介绍TypeScript中类的装饰器。
可以把类的装饰器看成是一个函数,通过装饰器可以对一个类添加额外的信息(属性、方法)。
定义装饰器
定义方法,接收类的构造函数为参数。
function testDecorator(constructor: any) {
console.log('testDecorator')
}
使用装饰器
使用装饰器很简单,在类上面使用@
符添加装饰器注解就可以了。
@testDecorator
class Test{}
运行时机
装饰器的运行时机是类创建后立即执行。
修改类行为
通过在装饰器方法中,对类的构造函数添加自定义方法实现修改类行为。
function testDecorator(constructor: any) {
constructor.prototype.getName = () => {
console.log('testDecorator')
}
}
@testDecorator
class Test{}
const test = new Test();
(test as any).getName()
多个装饰器的调用流程
如果注册了多个装饰器,那么执行流程是从下到上,先注册的后执行。
装饰器进阶
函数返回不同类型的装饰器。
function testDecorator(flag: boolean) {
if (flag) {
return function(constructor: any) {
constructor.prototype.getName = () => {
console.log('testDecorator')
}
}
} else {
return function (constructor: any) { }
}
}
@testDecorator(true)
class Test{
}
const test = new Test();
(test as any).getName()