sookie
sookie

Reputation: 2517

Access child constructor from base class constructor

Given the following class hierarchy: ChildClass extends ParentClass, is it possible to access the ChildClass constructor function from the ParentClass constructor? For example:

class ChildClass extends ParentClass
{
    constructor()
    {
        super()
    }
}

ChildClass.prop = 'prop'

class ParentClass
{
    constructor()
    {
        if (this._child().prop == 'prop') // here
        {
            console.log("All ok");
        }
    }

    get _child()
    {
        return this.constructor;
    }
}

In other words, what I'm trying to do is access the child's 'static' property for verification purposes

Upvotes: 2

Views: 449

Answers (2)

Estus Flask
Estus Flask

Reputation: 222369

It should be this._child instead of this._child(), because child is property accessor, not a method:

class ParentClass
{
    constructor()
    {
        if (this._child.prop == 'prop')
        {
            console.log("All ok");
        }
    }

    get _child()
    {
        return this.constructor;
    }
}

_child getter is redundant and misleading. Usually this.constructor is used directly:

class ParentClass
{
    constructor()
    {
        if (this.constructor.prop == 'prop')
        {
            console.log("All ok");
        }
    }
}

Referring to 'child' in parent class is semantically incorrect (a parent doesn't and shouldn't 'know' about its children, and _child can be a parent itself), but referring to this is not.

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 121998

is it possible to access the ChildClass constructor function from the ParentClass constructor?

Every Child is a Parent but not every Parent is a Child.

No. You can't. Even if possible with some dirty codes, don't do it. Rethink about your design. In the chain of Inheritance every Child should inherit the properties of Parent. Not the reverse.

Just think that there are 3 children and which children's props you get ? Bummer.

Upvotes: 5

Related Questions