javascript - 在javascript中动态获取所有类函数
问题描述
如何获取我的所有类的函数及其继承的类的函数的数组
例如
class Foo extends Bar {
funcA() {}
}
class Bar {
funcB() {}
}
const instanceFoo = new Foo();
getClassFunctions(instanceFoo); // should return an array ['funcA', 'funcB'];
我做了一个返回类的函数名的函数,但它只适用于类自己的属性
const getAllFuncs = (obj) => {
const proto = Object.getPrototypeOf (obj);
const names = Object.getOwnPropertyNames (proto);
return names.filter (name => typeof obj[name] === 'function' && name !== 'constructor');
}
解决方案
简单地循环,去每个原型,当你到达时可能会停止Object.prototype
。我也会从对象本身开始,而不是它的原型,因为可以在构造过程中添加方法:
const getAllFuncs = (obj) => {
// Remember which names we've checked
const checked = new Set();
// The function names we'll return
const funcs = [];
while (obj && obj !== Object.prototype) {
for (const name of Object.getOwnPropertyNames(obj)) {
if (name !== "constructor" && !checked.has(name)) {
// Remember we've checked this name
checked.add(name);
const value = obj[name];
if (typeof value === "function") {
// Remember this function
funcs.push(name);
}
}
}
// Go up a level
obj = Object.getPrototypeOf(obj);
}
return funcs;
};
原因checked
与funcs
一个对象可能有一个以foo
非函数命名的属性不同,但它的原型也可能有一个foo
带有函数的属性。这很少见,但可行:
class Base {
foo() {
}
}
class Sub extends Base {
constructor() {
super();
this.foo = 42;
}
}
const sub = new Sub();
const names = getAllFuncs(sub);
names
不包括foo
因为sub.foo
is 42
,而不是函数。
推荐阅读
- git - How can I see the full list of commits and not only the recent ones?
- snowflake-cloud-data-platform - How to find a second/third occurrence in a string in Snowflake/SQL
- python - Delete rows in reverse but skip header row
- javascript - 用某个类替换所有元素
- integration - Dell Boomi - 从电子邮件正文中解析值
- javascript - 从 useEffect 返回的数据无限滚动/错误
- java - 试图将 Card 对象传递给 ArrayList
- java - 通过循环 arraylist 来填充 setter
- enums - 如何在函数中增加传递的枚举?
- python - 出现“不支持解码 str”错误