给定一个类如下,我可以通过它的所有console.log

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()?
});

我的问题是如何调用所有方法来代替PropertyNames

最佳答案

你可以这样写:

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())

关于javascript - 调用原型(prototype)的所有方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47111543/

10-11 22:11
查看更多