装饰器是一种特殊类型的声明,它能够被附加到类声明,方法, 访问符,属性或参数上。
类装饰器
const classDec: ClassDecorator = (target: Function) => {
target.prototype.myClassName = "类装饰器";
target.prototype.getClassName = <T>(params: T, param2: number) => {
console.log(`我是方法里的${params}${param2}`);
return params;
};
};
@classDec
class MyClassD {}
let myClassD = new MyClassD();
// console.log(myClassD)
// console.log((myClassD as any).myClassName)
// console.log((myClassD as any).getClassName(123,'zhang'));
工厂装饰器
其实也就是一个高阶函数 外层的函数接受值 里层的函数最终接受类的构造函数
⭐相同函数名称只执行先注册的
const facDec = (params:string): ClassDecorator => {
return (fun:Function)=>{
fun.prototype.say = ()=>{
console.log(`i say${params}`)
}
};
};
@facDec('世界和平')
class MyFacDec{
say(){
}
}
let myFacDec = new MyFacDec()
myFacDec.say()
装饰器组合
@watcher2('myYname')
@watcher
class AA {
constructor() {
}
}
const aaTest = new AA();
console.log((aaTest as any).getParams('123wode'));
console.log((aaTest as any).getOptions());
方法装饰器
//普通方法装饰器
const methodDec: MethodDecorator = (
target,
propertyKey,
descriptor: PropertyDescriptor
) => {
const method = descriptor.value;
descriptor.value = () => {
console.log(`重写方法`);
};
};
//静态方法装饰器
const staticMethodDec: MethodDecorator = (
target,
propertyKey,
descriptor: PropertyDescriptor
) => {
const method = descriptor.value;
descriptor.value = () => {
console.log(`重写静态方法`);
};
};
class MyMethod {
@methodDec
public showMethod() {
console.log(`来吧展示普通方法`);
}
@staticMethodDec
public static showStaticMethod() {
console.log(`来吧展示静态方法`);
}
}
let myMethodD = new MyMethod();
// console.log(myMethodD)
// myMethodD.showMethod()
// MyMethod.showStaticMethod()
属性装饰器
const proDec: PropertyDecorator = (target, propertyKey) => {
let myvalue: string;
Object.defineProperty(target, propertyKey, {
get() {
return myvalue.toLocaleLowerCase();
},
set(v) {
myvalue = v;
},
});
};
class Student {
@proDec
public name: string;
public age: number;
constructor(n: string, a: number) {
this.name = n;
this.age = a;
}
say() {
console.log(`${this.name}age is ${this.age}`);
}
}
let xiaogang = new Student("ZhAngsan", 19);
// xiaogang.say()
// console.log(xiaogang.name)
元数据
Reflect.defineMetadata("myname", "12", myFacDec,'title');
console.log(Reflect.getMetadata("myname",myFacDec,'title'))