
求教:如下类运行的时候,如何在 constructor 中获得 App 所定义的方法名称
class App { constructor() { // 如何在这里获得 App 下面的所有方法? } play() {} unplay() {} pause() {} dosome() {} dosome2() {} } new App() 1 LawlietZ 2023 年 8 月 1 日 this 里面 |
2 nkidgm 2023 年 8 月 1 日 不是有反射的 API 吗? Class 所有信息都可以拿到。 |
3 logAn7 2023 年 8 月 1 日 Class<App> appClass = App.class; Method[] methods = appClass.getDeclaredMethods(); |
4 USDT 2023 年 8 月 1 日 用 Reflect class App { constructor() { // 如何在这里获得 App 下面的所有方法? const {ownKeys, getPrototypeOf} = Reflect; console.log('methods:', ownKeys(getPrototypeOf(this))); // 多了一个 constructor ,自行 filter 下 } play() {} unplay() {} pause() {} dosome() {} dosome2() {} } new App() // output: [ 'constructor', 'play', 'unplay', 'pause', 'dosome', 'dosome2' ] |
6 airyland 2023 年 8 月 1 日 constructor() { this.proto = Object.getPrototypeOf(this); const methods = Object.getOwnPropertyNames(this.proto).filter(item => typeof this.proto[item] === 'function') console.log(methods) } |
7 lavvrence 2023 年 8 月 1 日 通过 Object.getOwnPropertyNames(App.prototype) 获取 App 类原型上的所有属性名称(包括方法名)。然后用 filter 筛选出类型为函数(方法)且不是 constructor 的属性 |
8 xiangyuecn 2023 年 8 月 1 日 这题我不会,所以,直接丢王炸: constructor() { var code=App+""; //从源码文本 code 中提取函数名字 } |
9 jifengg 2023 年 8 月 2 日 针对附言的回复:web 的“感谢”,是需要鼠标悬停才会显示的,悬停位置在楼号左边的回复按钮的左边 |
10 Belmode 2023 年 8 月 2 日 class App { constructor() { const funcs = Object.getOwnPropertyNames(Reflect.getPrototypeOf(this)).filter(it => it != 'constructor') console.log(funcs) } play() {} unplay() {} pause() {} dosome() {} dosome2() {} } new App() |