1、类装饰器(用于为类新增、更改属性和方法)
function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
return class extends constructor {
newProperty = "new property";
hello = "override";
}
}
@classDecorator
class Greeter {
property = "property";
hello: string;
constructor(m: string) {
this.hello = m;
}
}
console.log(new Greeter("world"));
// {
// "property": "property",
// "hello": "override",
// "newProperty": "new property"
// }
2、类方法装饰器
function enumerable(target: any, propertyKey: string, descriptor: PropertyDescriptor){
console.log('执行say之前做的操作')
//返回原型对象、key、成员属性的描述符
}
class Greeter {
property = "property";
hello: string;
@enumerable
say(){
}
constructor(m: string) {
this.hello = m;
}
}
3、类属性装饰器
function enumerable(target: any, key:string){
console.log(target)
console.log(key)
//返回原型对象、key
}
class Greeter {
@enumerable
property = "property";
hello: string;
say(){
}
constructor(m: string) {
this.hello = m;
}
}