類的方法的裝飾器
- 方法的裝飾器的執(zhí)行時(shí)間也是在類定義之后戚啥,立即對(duì)類的方法進(jìn)行裝飾修改
- 方法的裝飾器接受3個(gè)參數(shù) target奋单、key、descriptor
- 普通方法 target 對(duì)應(yīng)的是類的prototype, key對(duì)應(yīng)的是裝飾的方法的名字
- 靜態(tài)方法(static) target 對(duì)應(yīng)的是類的構(gòu)造函數(shù), key對(duì)應(yīng)的是裝飾的方法的名字
function getNameDecorator(target: any, key: string,descriptor: PropertyDescriptor) {
// console.log(target,key);
};
class Test{
name: string;
constructor(name: string) {
this.name = name;
}
@getNameDecorator
getName() {
return this.name;
}
// static getName() {
// return '123';
// }
}
// const test = new Test('yang');
// console.log(test.getName());
descriptor參數(shù)就是對(duì)方法的 PropertyDescriptor屬性(value,enumerable,configurable,writable )做一些編輯
class Test{
name: string;
constructor(name: string) {
this.name = name;
}
@getNameDecorator
getName() {
return this.name;
}
}
// 默認(rèn)情況下 descriptor的writable為true猫十,也就是可以被修改览濒。false時(shí)是只讀的
const test = new Test('yang');
test.getName = () => {
return '123';
}
console.log(test.getName()); // 123
- 當(dāng)我們修改descriptor的writable為false的時(shí)候,就不能去改寫(xiě)getName 方法了炫彩,否則會(huì)報(bào)錯(cuò)
- 當(dāng)然了匾七,就算是descriptor的writable為false的時(shí)候,我們也可以通過(guò)對(duì)descriptor的value進(jìn)行變更江兢。從而達(dá)到對(duì)原來(lái)的方法的變更昨忆。因?yàn)関alue就是屬性的值,而此時(shí)value的值就是getName方法杉允。
function getNameDecorator(target: any, key: string,descriptor:PropertyDescriptor) {
// console.log(target,key);
descriptor.writable = false;
descriptor.value = function () {
return 'decorator'
}
};
class Test{
name: string;
constructor(name: string) {
this.name = name;
}
@getNameDecorator
getName() {
return this.name;
}
}
const test = new Test('yang');
console.log(test.getName()); // decorator