[英]How do you get a list of all class children in JavaScript?
I have a lot of classes, but for this question I'll simplify it a bit. 我有很多课程,但是对于这个问题,我将简化一下。
class A {
}
class B extends A {
}
class C extends A {
}
class D extends C {
}
Now my question is: how do you get a list of (all, not only direct) children of a class? 现在我的问题是:如何获得班级的所有(不仅是直接的)孩子名单? So,
A.getChildren()
would be [B, C, D]
and C.getChildren()
would be [D]
. 因此,
A.getChildren()
将为[B, C, D]
而C.getChildren()
将为[D]
。 By the way, I'm only looking for pure JavaScript solutions. 顺便说一句,我只是在寻找纯JavaScript解决方案。
Maybe this isn't even possible and I need to approach this from a whole different way, like registering every class in its parent class. 也许这甚至是不可能的,我需要以一种完全不同的方式来解决这个问题,例如在其父类中注册每个类。
So, is there a simple function (written or just built-in) that could do this, and if it's not even possible, in what other way should I solve this problem? 那么,是否有一个简单的函数(编写的或仅内置的)可以做到这一点,如果甚至不可能,我应该以其他方式解决此问题吗?
If you have control over A
's constructor and if every class is instantiated at least once, then you can put a line in the constructor which adds the child class to a Set
: 如果您可以控制
A
的构造函数,并且每个类至少实例化一次,则可以在构造函数中放置一行以将子类添加到Set
:
const classes = new Set(); class A { constructor() { classes.add(this.constructor); } } class B extends A { } class C extends A { } class D extends C { } new B(); new B(); new C(); new D(); console.log([...classes]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.