本篇文章将介绍TypeScript中类方法的装饰器。
类方法装饰器的定义
// 类方法装饰器 target 对应的是类的 prototype
function funcDescriptor(target:any,key:string) { }
class Test3 {
name: string
constructor(name: string) {
this.name = name
}
@funcDescriptor
getName() {
return this.name
}
}
定义类的时候就会对类中的方法进行装饰。
类属性修改控制
可以使用类方法装饰器参数中的descriptor
对类属性的读写进行控制。
function funcDescriptor(target: any, key: string, descriptor: PropertyDescriptor) {
// 可以修改属性值
descriptor.writable = true
}
对类方法进行变更
可以对类方法的返回值进行变更:
const test4 = new Test3('jake')
test4.getName = () => {
return '122'
}
这时候输出的就是修改后方法的返回值了。
使用装饰器对类的返回值进行变更
通过descriptor
可以拿到类方法的引用,从而对方法进行变更。
function funcDescriptor(target: any, key: string, descriptor: PropertyDescriptor) {
descriptor.value = function () {
return 'decorator'
}
}
class Test3 {
name: string
constructor(name: string) {
this.name = name
}
@funcDescriptor
getName() {
return this.name
}
}
const test4 = new Test3('jake')
console.log(test4.getName())
这时候输出的就是装饰器变更后的返回值了。