简体   繁体   English

您如何获取JavaScript中所有班级孩子的列表?

[英]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.

相关问题 如何使用Javascript获取所有孩子(即孩子的孩子)? - How do i get all children (ie children of children) with Javascript? 如何将Firebase中特定ref的所有子级放入对象? - How do you get all the children of specific ref in firebase into an object? 如何使用Javascript从列表中获取类的静态变量的值 - How do you get the value of a static variable of a class from a list with Javascript 如何在Javascript中获取subArray的所有子级 - How to get all children of a subArray in Javascript 如何让所有孩子的文字以 ; 分隔在 JavaScript 中? - How to get all children text separated by ; in javascript? jquery / javascript:如何从父元素的所有子元素中删除“活动”类? - jquery/javascript: How do I remove the 'active' class from all the children of a parent element? 你如何循环遍历 javascript 中未知数量的孩子和孩子的孩子 - How do you loop through an unknown amount of children and children of children in javascript 如何获取JavaScript中某个类的所有静态成员的列表 - How to get list of all static members of some class in javascript 如何在javascript中以列表形式获取具有类名称的所有元素 - How to get all elements with class name in list form in javascript Javascript得到所有直接的孩子 - Javascript get all direct children
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM