Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a list of statics on an ES6 class

Given an ES6 class, how can I inspect it to determine its gettable static properties and methods?

In ES5 determining the statics attached to a class (it's constructor) was as simple as iterating over the properties of the function. In ES6, is appears there is some magic going on that doesn't expose them as such.

like image 552
Allain Lalonde Avatar asked Oct 11 '15 20:10

Allain Lalonde


2 Answers

Yes, all methods of classes are non-enumerable by default.

You still can iterate them using Object.getOwnPropertyNames. Filter out .prototype, .name and .length (or just everything that is not a function). To include inherited static methods, you will have to walk the prototype chain explicitly (using Object.getPrototypeOf).

like image 185
Bergi Avatar answered Nov 15 '22 10:11

Bergi


If you want to get a dynamic list of standard class property names (so that you can filter them out of your list of static members), you can simply get the property names from an empty class:

const standardClassProps = Object.getOwnPropertyNames(class _{});

// ["length", "prototype", "name"]

This will produce a reasonably future-proof array that will dynamically adapt to changes to the standard, especially the addition of new standard static properties.

class Foo {
    static bar() {}
}

function isOwnStaticMember(propName) {
    return !standardClassProps.includes(propName);
}

const staticMembers = Object.getOwnPropertyNames( Foo ).filter(isOwnStaticMember);

// ["bar"]
like image 21
JDB Avatar answered Nov 15 '22 11:11

JDB