37

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.
});
eguneys
  • 6,028
  • 7
  • 31
  • 63

2 Answers2

48

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.

Andrey Ermakov
  • 3,298
  • 1
  • 25
  • 46
0

There is no iterator / getter method like Object.keys in ES6 (yet?). you can, however, use for-of to iterate over the keys:

function getKeys(someObject) {
    return (for (key of Object.keys(someObject)) [key, someObject[key]]);
}

for (let [key, value] of getKeys(someObject)) {
    // use key / value here
}
Cerbrus
  • 70,800
  • 18
  • 132
  • 147