前置知识:
class b {
val = 999;
get bv() {
return this.val;
}
set bv(v) {
this.val = v;
}
}
let ins = new b();
console.log(ins.bv); //999
ins.bv = 888;
console.log(ins.bv); //888
?类可以在一个方法前加 get / set 设置该方法的行为;
而 get / set 装饰器就是用来替代原来的 get/set 方法内的逻辑;
class b {
val:any = 999;
@myGet
get bv() {
return this.val;
}
set bv(v) {
this.val = v;
}
}
function myGet(value: any, context: ClassGetterDecoratorContext){
return function(){
return '替换原来的get'
}
}
let ins = new b();
console.log(ins.bv); //'替换原来的get'
class b {
val: any = 999;
@mySet("替代自身set")
set bv(v: any) {
this.val = v;
}
get bv() {
return this.val;
}
}
function mySet(setVal: string) {
return function (value: any, context: ClassSetterDecoratorContext) {
return function (this: any) {
this.val = setVal;
};
};
}
let ins = new b();
ins.bv = 888;
console.log(ins.bv); //替代自身set