装饰器
了解
- 装饰器是一种特殊类型的声明,它能够被附加到类的声明、方法、属性或参数上,可以修改类的行为
- 通俗的来讲修饰器就是一个方法,可以注入到类、方法、属性参数上来扩展类、属性、方法、参数的功能
- 常见的修饰器有类修饰器、方法修饰器、参数修饰器
装饰器全家桶
装饰器家族有 4 种装饰形式,注意,装饰器能装饰在类、方法、属性和参数上,但不能只装饰在函数上!
写法
普通修饰器(无法传参)、修饰器工厂(可传参)
类装饰器
- 类装饰器表达式会在运行时当做函数被调用,类的构造函数作为其唯一的参数
- 类修饰器在类声明之前被声明(紧靠着类声明)。
- 类修饰器应用于类构造函数,可以用来监视、修改或替换类定义
- 装饰器(不可传参)
function logClass(params: any) {
// params 就是当前类
console.log(params);
console.log('装饰器调用了)
params.prototype.apiUrl = '111'
}
@logClass // 不能加 分号 @logClass; ×
class Http{ } // 装饰器调用了
var http:any = new Http();
console.log(http.apiUrl);
- 装饰器工厂(传递参数)
// 类装饰器也可传递参数(装饰器工厂)
function logClass(params: string) {
return function(target: any) {
console.log(params); // Hello 赋 给了 params
console.log(target); // 当前类赋值给了 target
target.prototype.api = params
};
}
@logClass('http://www.baidu.com')
class HttpClient {}
var http: any = new HttpClient();
console.log(http.api);
- 创造构造函数的例子
function logClass(target:any) {
return class extends target{
apiUrl: string = '我是修改后的 apiUrl'
getApi(){
this.apiUrl ='--------'+ this.apiUrl + '--------'
console.log(this.apiUrl);
}
}
}
@logClass
class HttpClient{
public apiUrl!: string
constructor(){
this.apiUrl = '我是默认的 apiUrl '
}
getApi(){
console.log(this.apiUrl);
}
}
var http = new HttpClient();
http.getApi();
属性装饰器
- 属性装饰器表达式会在运行是当做函数被调用,传入下列两个参数
- 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象
- 成员的名字
function attrDecorator(target: any, propertyKey: string){
console.log(target) // 对于静态成员来说, 是类的构造函数, 对于实例成员是类的原型对象
console.log(propertyKey) // 成员的名称
}
class User {
@attrDecorator
name: string | undefined
}
方法装饰器
方法装饰器表达式会在运行时,当作函数被调用,传入下列 3个参数
- 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象
- 成员的名字
- 成员的属性描述符
{ value: any, writable: boolean, enumerable: boolean, configurable: boolean }
function methodDecorator(target: any, propertyKey: string, descripter: PerportyDescripter){
console.log(target) // 对于静态成员来说, 是类的构造函数, 对于实例成员是类的原型对象
console.log(propertyKey) // 成员的名称
console.log(descripter) // 成员属性描述符
}
class User{
name: string | undefined
@methodDecorator
getName(){
console.log(this.name)
}
}
访问器修饰符
和函数修饰符一样, 只不过是放在 访问器 上
function fwqDecorator(params: string){
return function(target: any, peroprotyKey: string, descriptor: PropertyDescriptor){
console.log(target) // 对于静态成员来说, 是类的构造函数, 对于实例成员是类的原型对象
console.log(propertyKey) // 成员的名称
console.log(descripter) // 成员属性描述符
}
}
class User {
private _name: string;
// 装饰在访问器上
@fwqDecorator('zMao')
get name(){
conosle.log(this._name)
}
}
参数装饰器
参数装饰器表达式会在运行时当做函数被调用,传入下列 3个参数
- 对于静态成员来说是类的构造函数,对于实例成员来说是类的原型对象
- 成员名称
- 参数在函数参数列表中的索引
let required = function (target: any, propertyKey: string, parameterIndex: number) {
console.log(target) // 对于静态成员来说是类的构造函数,对于实例成员来说是类的原型对象
console.log(propertyKey) // 成员名称
console.log(parameterIndex) // number
}
class User {
ptivate _name: string | undefined
set name(@required name: string){
this._name = name
}
}