Jan Jan - 10 months ago 44
Javascript Question

Get functions (methods) of a class

I have to dynamically fetch the properties and functions of a ES6 class. Is this even possible?

Using a for...in loop, I only get to loop through the properties of a class instance:

class Foo {
constructor() {
this.bar = "hi";
someFunc() {
var foo = new Foo();
for (var idx in foo) {



Answer Source

This function will get all functions. Inherited or not, enumerable or not. All functions are included.

function getAllFuncs(obj) {
    var props = [];

    do {
        props = props.concat(Object.getOwnPropertyNames(obj));
    } while (obj = Object.getPrototypeOf(obj));

    return props.sort().filter(function(e, i, arr) { 
       if (e!=arr[i+1] && typeof obj[e] == 'function') return true;

Do test


console output:

["constructor", "toString", "toLocaleString", "join", "pop", "push", "concat", "reverse", "shift", "unshift", "slice", "splice", "sort", "filter", "forEach", "some", "every", "map", "indexOf", "lastIndexOf", "reduce", "reduceRight", "entries", "keys", "constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "__defineGetter__", "__lookupGetter__", "__defineSetter__", "__lookupSetter__"]