如何获得 class 内部的方法?

280 天前
 humbass

求教:如下类运行的时候,如何在 constructor 中获得 App 所定义的方法名称

class App {
  constructor() {
    // 如何在这里获得 App 下面的所有方法?
  }
  play() {}
  unplay() {}
  pause() {}
  dosome() {}
  dosome2() {}
}
new App()
1694 次点击
所在节点    Node.js
10 条回复
LawlietZ
280 天前
this 里面
nkidgm
280 天前
不是有反射的 API 吗?

Class 所有信息都可以拿到。
logAn7
280 天前
Class<App> appClass = App.class;
Method[] methods = appClass.getDeclaredMethods();
USDT
280 天前
用 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' ]
logAn7
280 天前
@logAn7 呃呃我审题不认真了😫
airyland
280 天前
constructor() {
this.proto = Object.getPrototypeOf(this);

const methods = Object.getOwnPropertyNames(this.proto).filter(item => typeof this.proto[item] === 'function')

console.log(methods)
}
jaylee4869
280 天前
通过 Object.getOwnPropertyNames(App.prototype) 获取 App 类原型上的所有属性名称(包括方法名)。然后用 filter 筛选出类型为函数(方法)且不是 constructor 的属性
xiangyuecn
280 天前
这题我不会,所以,直接丢王炸:

constructor() {
var code=App+"";
//从源码文本 code 中提取函数名字😂
}
jifengg
280 天前
针对附言的回复:web 的“感谢”,是需要鼠标悬停才会显示的,悬停位置在楼号左边的回复按钮的左边
Belmode
280 天前
class App {
constructor() {
const funcs = Object.getOwnPropertyNames(Reflect.getPrototypeOf(this)).filter(it => it != 'constructor')
console.log(funcs)
}
play() {}
unplay() {}
pause() {}
dosome() {}
dosome2() {}
}

new App()

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/961639

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX