如何枚举ES6类的方法?如同Object.keys
这是一个例子:
class Callbacks {
method1() {
}
method2() {
}
}
const callbacks = new Callbacks();
callbacks.enumerateMethods(function(method) {
// method1, method2 etc.
});
Object.keys()
仅迭代对象的可枚举属性。而ES6方法不是。您可以使用getOwnPropertyNames()
。另外,方法是在对象的原型上定义的,因此您需要Object.getPrototypeOf()
获取它们。工作示例:
for (let name of Object.getOwnPropertyNames(Object.getPrototypeOf(callbacks))) {
let method = callbacks[name];
// Supposedly you'd like to skip constructor
if (!(method instanceof Function) || method === Callbacks) continue;
console.log(method, name);
}
请注意,如果将Symbols用作方法键,则需要使用getOwnPropertySymbols()
它们来遍历它们。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句