装饰器
装饰器是一种特殊类型的声明,它能够被附加到类声明,方法,属性或参数上,可以修改类的行为。
通俗的讲,装饰器就是一个方法,可以注入到类、方法、属性、参数上来扩展类、方法、属性、参数的功能。
常见的装饰器有:普通装饰器(无法传参)、装饰器工厂(可传参)
装饰器类型
- 类装饰器
- 属性装饰器
- 方法装饰器
- 函数参数装饰器
类装饰器
- 类装饰器在类声明之前被声明(紧靠着类声明);
- 类装饰器应用于类构造函数,可以用来监视、修改或替换类定义;
- 类的构造函数将作为唯一参数传递给装饰器;
- 如果类装饰器返回一个值,它会使用返回的构造函数替换原来的类声明;
// 类装饰器(target 就是当前类)---- 普通装饰器(无法传参)
function logClass(target: any) {
console.log(target);
target.prototype.apiUrl = 'dfdjfadgadgadjfad';
target.prototype.run = function() {
console.log('这是扩展的run方法');
}
}
@logClass
class HttpClient {
constructor() {
}
getData() {
}
}
var http:any = new HttpClient();
console.log(http.apiUrl);
http.run();
// 类装饰器 ---- 装饰器工厂(可传参)
function logClass(params: string) {
console.log(params);
// target 就是当前类
return function(target: any) {
console.log(target);
console.log(params);
target.prototype.apiUrl = params;
}
}
@logClass('http://www.baidu.com')
class HttpClient {
constructor() {
}
getData() {
}
}
var http: any = new HttpClient();
console.log(http.apiUrl);
// 类装饰器重载构造函数
// 类装饰器表达式会在运行时当作函数被调用,类的构造函数作为其唯一的参数
// 如果类装饰器返回一个值,它会使用提供的构造函数来替换类的声明
function logClass(target: any) {
console.log(target);
return class extends target {
apiUrl: any = '我是修改后的apiUrl';
getData() {
this.apiUrl += '----'
console.log(this