3-13 方法拦截器作业
来源:3-13 实战晋级: TS 静态成员、方法拦截器在大中项目中的实战+作业

终有一死
2023-04-08
class People {
name: string;
age: number;
addr: string;
static count: number = 0;
constructor(_name: string, _age: number, _addr: string) {
this.name = _name;
this.age = _age;
this.addr = _addr;
People.count++;
}
doEat(who: string, where: string) {
console.log(`who:${who}, where:${where}`);
}
doStep() {}
}
class StringUtil {
static trimSpace(str: string) {
return str.replace(/\s+/g, '')
}
}
// 作业 --- 通用的方法拦截器
const funcIntercepter = function(needHandleClass: any, funcName: string): void {
const dataProp = Object.getOwnPropertyDescriptor(needHandleClass.prototype, funcName)
const targetMethod = dataProp!.value
dataProp!.value = function(...args: any[]) {
args = args.map( arg => {
if (typeof arg === 'string') return StringUtil.trimSpace(arg)
return arg
})
console.log('前置拦截...');
targetMethod.apply(this, args);
console.log('后置拦截...');
}
Object.defineProperty(needHandleClass.prototype, 'doEat', dataProp!)
}
// dataProp1?.value('王明') // 这样调用, this 就指向 dataProp1
let p = new People('lisi', 16, 'beijing');
funcIntercepter(People, 'doEat')
p.doEat('w ang wu', 's hangh ai') // 此时 this 指向 实例 p
export {}
写回答
1回答
-
keviny79
2023-06-26
因为作业很有代表性,为保证每个同学都有一次作业机会,老师在课程 第2章第3节(2-3节) 对如何提交作业或作业问题有了详细说明。 为了进一步提升技能和达到作业的效果,所有必做作业大家务必先做一次,然后通过课程群发给老师,我再发答案。
10
相似问题
麻烦老师看下有没问题
回答 1
5-8 TS 继承底层源码解析作业
回答 1