简体   繁体   中英

JavaScript: How to get child Class's methods in parent's constructor?

How to get ( console.log for ex.) B class's methods in A class's constructor?

class A {
    constructor() {
        // GET B's method names ('ok', ...) here
    }
}

class B extends A {
    constructor() {
        super();
    }

    ok() {

    }
}

Use either new.target.prototype or Object.getPrototypeOf(this) to get the prototype object of the instantiated subclass. Then traverse the prototype chain to all superclasses, and get the own properties of each object. Don't forget non-enumerable properties.

Of course, using this in a constructor for more than logging/debugging purposes is a code smell. A class should not need to know about its subclasses. If you want to do autobindings, let each subclass constructor autobind its own methods.

In the "base" constructor you have access to complete object, so can check what is its real constructor and so its prototype const childClassPrototype = this.constructor.prototype . Having a "child" prototype you can get a list of its properties with Object.getOwnPropertyNames(childClassPrototype) . From that list you want to filter out "constructor" and properties that are not functions.

Note: this technique will only give you access to "leaf" prototype, once you may have a multi level prototype chain. Thus you have to iterate over prototype chain.

Note2: for autobinding you may like to consider using a decorator. One implementation is here: https://github.com/andreypopp/autobind-decorator - this technique gives you better control over unexpected behavior that may come from metaprogramming

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM