方法装饰器
它会被应用到方法的 属性描述符上,可以用来监视,修改或者替换方法定义。
方法装饰会在运行时传入下列3个参数:
1、对于静态成员来说是类的构造函数,对于实例成员是类的原型对象。
2、成员的名字。
3、成员的属性描述符。
方法装饰器示例02:添加方法
//方法装饰器一
function get(params: any) {
return function (target: any, methodName: any, desc: any) {
console.log(target);
console.log(methodName);
console.log(desc);
target.apiUrl = "xxxx";
target.run = function () {
console.log("run");
};
};
}
class HttpClient {
public url: any | undefined;
constructor() {
}
@get("http://www.itying,com")
getData() {
console.log(this.url);
}
}
var http: any = new HttpClient();
console.log(http.apiUrl);
http.run();
方法装饰器示例02:修改方法
desc.value代表当前方法
function get(params: any) {
return function (target: any, methodName: any, desc: any) {
console.log(desc.value);
//修改装饰器的方法 把装饰器方法里面传入的所有参数改为string类型
//1、保存当前的方法
var oMethod = desc.value;
desc.value = function (...args: any[]) {
args = args.map((value) => {
return String(value);
});
oMethod.apply(this, args);
};
};
}
class HttpClient {
public url: any | undefined;
constructor() {
}
@get("http://www.itying,com")
getData(...args: any[]) {
console.log(args);
console.log("我是getData里面的方法");
}
}
var http = new HttpClient();
http.getData(123, "xxx");
装饰器的执行顺序
-
属性 > 方法 > 方法参数 > 类
-
如果有多个同样的装饰器,它会先执行后面的