调用原型的所有方法



给定如下所示的类,我可以console.log它的所有PropertyNames

class Security {
  constructor(param: ParamType) {
    this.method1(param);
    ...
    this.methodN(param);
  }
  method1(param){...};
  ...
  methodN(param){...};
}
Object.getOwnPropertyNames(Security.prototype).forEach( (value) => {
    console.log('Method: ', value);
    // value()?
});

我的问题是如何调用所有方法来代替// value()?

你可以写这样的东西:

class Security {
  method1(param) {
    console.log("M1");
  }
  method2(param) {
    console.log("M2");
  }
}
function callAll() {
  Object.getOwnPropertyNames(Security.prototype).forEach(value => {
    if (value !== 'constructor' && typeof Security.prototype[value] === 'function')
        this[value]();
  });
}
callAll.apply(new Security())

最新更新