How can I enumerate methods of an ES6 class? similar to Object.keys
Here's an example:
class Callbacks {
method1() {
}
method2() {
}
}
const callbacks = new Callbacks();
callbacks.enumerateMethods(function(method) {
// method1, method2 etc.
});
Object.keys()
iterates only enumerable properties of the object. And ES6 methods are not. You could use something like getOwnPropertyNames()
. Also methods are defined on prototype of your object so you'd need Object.getPrototypeOf()
to get them. Working example:
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);
}
Please notice that if you use Symbols as method keys you'd need to use getOwnPropertySymbols()
to iterate over them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With