admin管理员组

文章数量:1287511

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.

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.

Share Improve this question edited Sep 3, 2016 at 20:34 Michał Perłakowski 92.7k30 gold badges163 silver badges187 bronze badges asked Oct 11, 2015 at 20:16 Allain LalondeAllain Lalonde 93.4k72 gold badges189 silver badges238 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 13

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).

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"]

本文标签: javascriptGetting a list of statics on an ES6 classStack Overflow