纯属个人学习,加深记忆使用。
装饰器
一种特殊类型的声明,能够被附加到类、方法、属性或参数上,可以修改类的行为
类装饰器
function logClass(params: any) { //类装饰器
console.log(params); //params就是当前类
params.prototype.apiUrl = '动态扩展的属性';
params.prototype.run = function () {
console.log("动态扩展的方法")
}
}
@logClass
class HttpClient {
constructor() {
}
getData() {
}
}
let http: any = new HttpClient();
console.log(http.apiUrl);
http.run();
装饰器工厂(可传参)
function logClass(params: string) { //类装饰器
return function (target: any) {
console.log(target); //当前类
console.log(params); //传入的参数
target.prototype.apiUrl = params;
}
}
@logClass('http://www.hello.com/api')
class HttpClient {
constructor() {
}
getData() {
}
}
let http:any= new HttpClient();
console.log(http.apiUrl);
类装饰器重载构造方法
function logClass(target:any){
return class extends target{
apiUrl:any="我是修改后的数据";
getData(){
console.log(this.apiUrl)
}
}
}
@logClass
class HttpClient {
public apiUrl: string | undefined
constructor() {
this.apiUrl = '构造函数里的apiUrl'
}
getData() {
console.log(this.apiUrl);
}
}
属性装饰器
function logProperty(params: any) {
return function (target: any, attr: any) {
console.log(target); //当前的类
console.log(attr); //属性成员的名称
target[attr] = params;
}
}
class HttpClient {
@logProperty('http://hello.com')
public apiUrl: string | undefined
constructor() {
}
getData() {
}
}
方法装饰器
function get(params: any) {
return function (target: any, MethodName: any, desc: any) {
console.log(target);//原型对象
console.log(MethodName); //当前方法的名称
console.log(desc);//当前的方法的属性描述
//修改装饰器的方法 把装饰器的方法里面传入的所有参数改为string类型
//1.保存档当前的方法
let oMerhod = desc.value;
desc.value = function (...args: any[]) {
args = args.map((value) => {
return String(value);
})
console.log(args);
oMerhod.apply(this.args)//不用apply会覆盖原来的方法
}
}
}
class HttpClient {
public apiUrl: string | undefined
constructor() {
}
@get('http://hello.com')
getData() {
console.log("我是getData里面的方法");
}
}
let h = new HttpClient();
h.getData(123,"xxx");
方法参数装饰器
function logParmars(params:any){
return function(target:any,paramsName:any,paramsIndex:any){
console.log(target); //当前类的原型对象
console.log(paramsName);//当前方法的名称
console.log(paramsIndex);//参数的索引位置
}
}
class HttpClient {
public apiUrl: string | undefined
constructor() {
}
getData(@logParmars('uuid') uuid:any) {
console.log("我是getData里面的方法");
}
}
装饰器的执行顺序
先后顺序为:
属性装饰器
方法装饰器
方法参数装饰器
类装饰器
如果有多个同样的装饰器,会先执行后面的装饰器