Find all classes in a Javascript application that extend a base class

后端 未结 3 2016
陌清茗
陌清茗 2020-12-17 18:08

I have code like this

class Animal{}
class Dog extends Animal {}
class Cat extends Animal {}
class Donkey extends Animal {}

I want to look

3条回答
  •  -上瘾入骨i
    2020-12-17 19:13

    I think you could make use of decorators. For instance, you could create @Extends() one and provide base class as an argument, e.g. @Extends(Animal). Inside the decorator function, you could take the name of the class decorated with @Extends and and put it into an array or an object. Don't know if it is applicable in browsers, but it should be. In Node with TypeScript I would do something like:

    import { MyClassMetadata } from './';
    
    export function Extends(parent): (...args: any[]) => void {
        return (target: object): void => {
            MyClassMetadata.someVariableToStoreChildren[parent.constructor.name].push(
                target,
            );
        }
    }
    

    Then you can access the MyClassMetadata variable that stores array of children of a given class and use it the way you want. You can play with it and get the desired result.

提交回复
热议问题