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!)
}
let p = new People('lisi', 16, 'beijing');
funcIntercepter(People, 'doEat')
p.doEat('w ang wu', 's hangh ai')
export {}