TypeScript TS类的方法拦截器实践

319 阅读1分钟

TS类的方法拦截器实践

应用场景:当多个Util工具类需要给内部方法,增加"开始前后的拦截器"用来"增加某些业务逻辑"时

一个一个的给工具类加太低效,这里实现一个简易的工共方法拦截器

class People {
  name: string
  age: number
  addr: string
  static count: number = 10
  constructor(_name: string, _age: number, _addr: string) {
    this.name = _name;
    this.age = _age;
    this.addr = _addr;
  }
  doEat(who: string, where: string) {
    console.log("who:" + who, "where:" + where);
  }
  doStep() { }
};

class StringUtil {
  static trimSpace(str: string) {
    return str.replace(/\s+/g, '');
  }
};

const dateProp1 = Object.getOwnPropertyDescriptor(People.prototype, 'doEat');
const targetMethod = dateProp1!.value;

dateProp1!.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(People.prototype, "doEat", dateProp1!);
let p = new People("peter", 23, "beijing");
p.doEat("张    三", "石 家 庄");