什么是修饰器
--装饰器(Decorator)是一种特殊类型的声明,它能够被附加到类声明,方法, 访问符,属性或参数上.修饰器必是一个函数,用来修改类的行为
- 方法参数修饰器
function logParams(params: any) {
return function (target: any, methodName: any, methodIndex: any) {
console.log(params); //xxxx
console.log(target); //方法原型
console.log(methodName); ///方法名getData
console.log(methodIndex); //方法参数索引
};
}
function logParams2(params: any) {
return function (target: any, methodName: any, methodIndex: any) {
console.log(params); //xxxx
console.log(target); //
console.log(methodName); ///方法名getData
console.log(methodIndex); //方法参数索引
};
}
class HttpClient {
constructor(public url: string) {}
getDate(@logParams("xxxx") uuid: any, @logParams2("xoxo") id: number) {
//从右到左执行顺序
console.log(uuid);
}
}
const http = new HttpClient("www.qkzer.com");
http.getDate("www.baidu.com", 5);
- 方法修饰器
function logMethod(params: any) {
return function (target: any, methodName: any, desc: any): void {
console.log(params); //修饰器实参 xxx
console.log(target); //原型对象
console.log(methodName); //方法名字 getData
console.log(desc); //描述---可以进行改写方法
desc.writable = false; //不可以被重写
var temp = desc.value;
desc.value = function (str: string): void {
//str:方法参数
console.log("修改" + "str");
temp(str);
temp.call(this, str);
// desc.value();
};
};
}
function funaDorn(target: any, methodName: any, desc: any): void {
console.log(target); //原型对象
console.log(methodName); //方法名字 getData
console.log(desc); //描述---可以进行改写方法
}
class goods {
// @logClass('dddd')
name: string | undefined;
constructor(str?: string) {
this.name = str;
}
@logMethod("xxxx")
@funaDorn
getData(str: string) {
console.log(str); //d
}
}
var d = new goods();
d.getData("d");
- 属性修饰器
function logClass(params:any){
return function(target:any,attrName:any):void{
console.log(params);//修饰器实参
target[attrName] = '武器';//在原型链上附加属性
console.log(target); //原型对象
console.log(attrName); //属性名字
}
}
class goods{
@logClass('dddd')
name:string | undefined
constructor(str?:string){
// this.name = str
}
}
var d = new goods();
console.log(d);
console.log(d.name);//武器
- 类修饰器
function logClass(target:any){
console.dir(target);//原型
return class extends target{
public name:any
getData(){ //重写类的方法
console.log(this);
console.log('新数据');
}
}
}
@logClass
class goods{
public name:string | undefined
constructor(str?:string){
this.name = str
}
getData(){
console.log(this);
console.log('原数据');
}
}
var d = new goods();
d.getData()
console.log(d);