Getting a list of statics on an ES6 class

前端 未结 2 1237
时光取名叫无心
时光取名叫无心 2020-11-29 13:19

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 construct

相关标签:
2条回答
  • 2020-11-29 13:55

    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"]
    
    0 讨论(0)
  • 2020-11-29 14:09

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

    0 讨论(0)
提交回复
热议问题