Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enumerate es6 class methods [duplicate]

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.
});
like image 927
eguneys Avatar asked Jul 15 '15 07:07

eguneys


1 Answers

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.

like image 50
Andrey Ermakov Avatar answered Oct 18 '22 21:10

Andrey Ermakov