Davit Yavryan
Davit Yavryan

Reputation: 298

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() {

    }
}

Upvotes: 0

Views: 1030

Answers (2)

chrmod
chrmod

Reputation: 1445

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

Upvotes: 1

Bergi
Bergi

Reputation: 664538

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.

Upvotes: 1

Related Questions