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.
Yes, all methods of class
es 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
).
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"]
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