获取JavaScript中的类方法

时间:2018-08-24 18:53:00

标签: javascript

如何获取为js中的类定义的方法的列表?

class c {
  methodA(){}
  static methodB(){}

  log(){console.log(/*methods*/);}
  static logStatic(){console.log(/*static methods*/)}
}

谢谢

1 个答案:

答案 0 :(得分:3)

您可以使用Object.getOwnPropertyNames并过滤instancestatic方法:

class c {
  methodA(){}
  static methodB(){}

  log(){console.log(/*methods*/);}
  static logStatic(){console.log(/*static methods*/)}
}
const instanceOnly = Object.getOwnPropertyNames(c.prototype)
    .filter(prop => prop != "constructor");
console.log(instanceOnly);
const staticOnly = Object.getOwnPropertyNames(c)
    .filter(prop => typeof c[prop] === "function");
console.log(staticOnly);