ts装饰器的执行时机
时间: 2023-08-24 18:08:52 浏览: 63
在TypeScript中,装饰器的执行时机取决于装饰的目标。以下是不同装饰器目标的执行时机:
1. 类装饰器:在类声明被定义时立即执行,而不是在实例化类或调用方法时执行。
2. 方法装饰器:在方法被定义时立即执行,而不是在方法被调用时执行。
3. 访问器装饰器:在访问器(getter或setter)被定义时立即执行,而不是在访问器被调用时执行。
4. 属性装饰器:在属性声明被定义时立即执行,而不是在属性被访问或赋值时执行。
注意,装饰器的执行顺序是从下往上,从右往左的。也就是说,如果一个类或方法上有多个装饰器,它们将按照从下到上、从右到左的顺序依次执行。
下面是一个示例,展示了不同类型装饰器的执行时机:
```typescript
function classDecorator(constructor: Function) {
console.log("Class decorator");
}
function methodDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log("Method decorator");
}
function accessorDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
console.log("Accessor decorator");
}
function propertyDecorator(target: any, propertyKey: string) {
console.log("Property decorator");
}
@classDecorator
class ExampleClass {
@propertyDecorator
property = "property";
@methodDecorator
method() {
console.log("Method called");
}
@accessorDecorator
get accessor() {
return this.property;
}
set accessor(value: string) {
this.property = value;
}
}
const example = new ExampleClass();
example.method();
console.log(example.accessor);
```
在上面的例子中,我们定义了一个类装饰器`classDecorator`,一个方法装饰器`methodDecorator`,一个访问器装饰器`accessorDecorator`和一个属性装饰器`propertyDecorator`。当我们创建`ExampleClass`的实例时,装饰器函数会按照指定的顺序执行。你可以运行代码查看控制台输出,以了解装饰器的执行时机。