1

As the title, using the class defined by es6 class, how to get all the subclasses of the specified base class?

For example, the following defines three classes A, B, C

Class A {}
Class B extends A{}
Class C extends A{}

How do I get all the subclasses of A? (=^-ω-^=)


Some people say that this question is meaningless. Hasn't Mu Meng encountered any situation in which multiple operations are switched according to the state? Is it more elegant to use if-else judgments one-by-one than using class to achieve polymorphism? ┐(̄ヮ ̄)┌


I have found a method available for me.

class A {}

const builder = (clazzMap => {
  return new class {
    // zhùcè yīgè class, chuàngjiàn zi lèi shí diàoyòng, yòng yú jìlù měi yīgè [zhuàngtài => zi lèi] duìyìng
    register(status, clazz) {
      clazzMap.Set(status, clazz)
      return this.Clazz
    }
    /**
     * huòqǔ yīgè biāoqiān zi lèi duìxiàng
     * @param {Number} index suǒyǐn
     * @returns {Tab} zi lèi duìxiàng
     */
    getInstance(index) {
      const clazz = clazzMap.Get(index)
      return new clazz()
    }
  }()
})(new Map())
builder.Register(1, class B extends A {})
builder.Register(2, class C extends A {})

Attachment: The problem is integrated into a blog, welcome to play here https://blog.rxliuli.com/p/e17d1a04/

rxliuli
  • 165
  • 1
  • 11
  • There is no record in Javascript of all subclasses of A. Each sub-class has a pointer to A, but not the other way around. – jfriend00 Jan 16 '19 at 04:44
  • I should add that this is also by design because classes can be created in private scope and they should be private (not findable from outside that scope). The only way I know of to do this would be to somehow register every subclass with some object that is enumerable so you can then enumerate a bunch of classes and see how many inherit from A. But, you'd have to do that manually - it is not done for you in the language in any way. – jfriend00 Jan 16 '19 at 04:55

0 Answers0