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 badges2 Answers
Reset to default 13Yes, 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"]
本文标签: javascriptGetting a list of statics on an ES6 classStack Overflow
版权声明:本文标题:javascript - Getting a list of statics on an ES6 class - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741314131a2371817.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论