【NestJS入门到精通】装饰器

目录

方法装饰器

ClassDecorator

定义了一个类装饰器 a,并将其应用于类 A。装饰器 a 会在类 A 被定义时执行。

javascript 复制代码
const a:ClassDecorator = (target:any)=>{
	console.log(target,target)//[class A] [class A]
}

@a
class A {
	constructor(){}
}

上面代码等价于下面代码

javascript 复制代码
const a:ClassDecorator = (target:any)=>{
	console.log(target,target)//[class A] [class A]
}

class A {
	constructor(){}
}
a(A)

通过prototype添加属性、方法

定义一个 ClassDecorator,这个装饰器的作用是修改类A 的原型,@a 装饰器为类 A 添加了一个 name 属性。具体来说,装饰器 aname 属性添加到了 A 类的 prototype 上,因此所有通过 A 类创建的实例都能够访问这个 name 属性。

javascript 复制代码
const a:ClassDecorator = (target:any)=>{
      target.prototype.name = "张三"
}

@a
class A {
	constructor(){}
}

const test:any = new A();
console.log(test)//A {}. 输出实例 A,内容包括 constructor 和原型链上的属性 `name`
console.log(test.name)//张三
  • 动态添加属性:使用装饰器,你可以动态为类或其实例添加属性、方法或者进行其他操作,而不需要直接修改类的定义。这使得代码更加灵活,可以根据上下文条件来修改类的行为。

  • 减少重复代码:如果你需要在多个类上应用相似的逻辑,比如为多个类都添加 name 属性,使用装饰器可以避免在每个类中都手动添加相同的代码。

  • 提高可读性:通过装饰器,相关的逻辑集中在一个地方,便于理解和维护。你可以将通用功能提取到装饰器中,而不是散落在多个类中。

属性装饰器

PropertyDecorator

  • target 是空对象 {},实际上是 A.prototype,这是因为 name 是实例属性,而实例属性存储在类的原型链中。
  • key 是 name,表示被装饰的属性名称。
javascript 复制代码
const a: PropertyDecorator = (target: any, key: string | symbol) => {
	console.log(target, key)//{} name
}

class A {
	@a
	public name: string;
	constructor() {
		this.name = "张三";
	}
}
  • 灵活的元数据处理:你可以在属性被定义时拦截并处理它,添加额外的行为或逻辑。例如,记录属性的变化、定义特定的验证规则等。

  • 解耦的功能增强:通过装饰器,你可以将逻辑与类的主要业务逻辑解耦开来。比如,可以为某个属性自动添加 getter/setter 方法,或者在装饰器中为属性附加元数据。

  • 代码简洁性:装饰器可以让代码更加简洁和可读,减少在类中重复编写相同的逻辑。

拓展

javascript 复制代码
const a: PropertyDecorator = (target: any, key: string | symbol) => {
	let value: string;
	Object.defineProperty(target, key, {
		get() {
			console.log( `修改后的值: ${value}`)// 修改返回的值
			return value
		},
		set(newvalue) {
			console.log(`${String(key)} 被赋值为 ${newvalue}`);
			value = newvalue;
		},
	});
};

class A {
	@a
	public name: string;
	constructor() {
		this.name = "张三"; // 当调用时,setter 会生效
	}
}

const test = new A();
test.name = "里斯"
console.log(test.name); 

打印的先后顺序

javascript 复制代码
name 被赋值为 张三
name 被赋值为 里斯
修改后的值: 里斯
里斯

装饰器在类定义的时候就会被执行

方法装饰器

  • target 是 A.prototype,即类 A 的原型对象,因为装饰器应用在类的实例方法 getName 上。
  • key 是被装饰方法的名称,在这里是 "getName"
  • descriptor 是方法的 属性描述符,包含关于方法的一些信息,例如可写性、可枚举性等。
javascript 复制代码
const a: MethodDecorator = (target: any, key: string | symbol,descriptor:any) => {
	console.log(target,key,'descriptor')
};
class A {
	public name: string;
	constructor() {
		this.name = "张三"; 
	}
	@a
	getName(){}
}
javascript 复制代码
// console.log(target,key,'descriptor') 打印结果
{} getName {
  value: [Function: getName],
  writable: true,
  enumerable: false,
  configurable: true
}

参数装饰器

需要用到ParameterDecorator装饰器,且装饰器的第三个参数parameterIndex为参数的索引,即第几个参数。

  • target:是方法所在类的原型对象。在这个例子中,target 为 {},这是 A.prototype,表示 A 类的原型。
  • propertyKey:是方法的名称。在这个例子中是 "getName",因为装饰器被应用在 getName 方法的参数上。
  • parameterIndex:是参数的索引。在这个例子中是 1,表示装饰器应用在 getName 方法的第二个参数(age)上。
javascript 复制代码
const a: ParameterDecorator = (target: Object, propertyKey: string | symbol | undefined, parameterIndex: number) => {
	console.log(target, propertyKey, parameterIndex); //{} getName 1
};

class A {
	public name: string;
	constructor() {
		this.name = "张三";
	}
	
	getName(name: string, @a age: number) {
		// age 参数被装饰器修饰
	}
}

在写参数装饰器可能会报错,比如:

原因是因为设定的参数类型,与定义的ParameterDecorator类型不一致。
ParameterDecorator类型如下:

其中 propertyKey: string | symbol | undefined

javascript 复制代码
declare type ParameterDecorator = (target: Object, propertyKey: string | symbol | undefined, parameterIndex: number) => void;

所以我们需要修改方法a的定义,上文已经是正确的定义方法。

javascript 复制代码
const a: ParameterDecorator = (target: Object, propertyKey: string | symbol | undefined, parameterIndex: number) => {
	console.log(target, propertyKey, parameterIndex); 
};
相关推荐
weixin_472339463 小时前
高效处理大体积Excel文件的Java技术方案解析
java·开发语言·excel
枯萎穿心攻击3 小时前
响应式编程入门教程第二节:构建 ObservableProperty<T> — 封装 ReactiveProperty 的高级用法
开发语言·unity·c#·游戏引擎
Eiceblue5 小时前
【免费.NET方案】CSV到PDF与DataTable的快速转换
开发语言·pdf·c#·.net
m0_555762905 小时前
Matlab 频谱分析 (Spectral Analysis)
开发语言·matlab
像风一样自由20205 小时前
HTML与JavaScript:构建动态交互式Web页面的基石
前端·javascript·html
浪裡遊6 小时前
React Hooks全面解析:从基础到高级的实用指南
开发语言·前端·javascript·react.js·node.js·ecmascript·php
lzb_kkk7 小时前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
好开心啊没烦恼7 小时前
Python 数据分析:numpy,说人话,说说数组维度。听故事学知识点怎么这么容易?
开发语言·人工智能·python·数据挖掘·数据分析·numpy
面朝大海,春不暖,花不开7 小时前
使用 Python 实现 ETL 流程:从文本文件提取到数据处理的全面指南
python·etl·原型模式
简佐义的博客8 小时前
破解非模式物种GO/KEGG注释难题
开发语言·数据库·后端·oracle·golang