vendredi 18 novembre 2016

ES6, access props set by the child from the parent's constructor

I am trying to set up a class hierarchy with ES6 classes.

All entities will inherit from single Base class. It will need to access properties exposed by the Child class in a generic manner. Like this:

class Base {
    constructor() {
        this.doSomethingWithProps();
    }

    doSomethingWithProps() {
        console.log(Object.keys(this));
    }
}

class Entity extends Base {
    constructor() {
        super();

        this.key = "value";
    }
}

Obviously, in the example above, Base class will not see the key prop set up by Entity. Ideally I would move the this assignment before super(), but that's not allowed. It would also be nice to be able to set properties before constructor, but AFAIK, that's not possible either.

The only solution I am left with is doing something like the following in each Entity:

class Base {
    doSomethingWithProps() {
        console.log(Object.keys(this));
    }
}

class Entity extends Base {
    constructor() {
        super();

        this.key = "value";

        this.doSomethingWithProps();
    }
}

However, besides being less than ideal, it will also create problems if I then want to inherit from Entity. doSomethingWithProps would then need to be able to detect if it's the "top-most" method in call hierarchy and only do its thing then. The only way to achieve that (that I can think of) would involve even more boilerplate.

Is there some solution I'm missing here? I'd be open to using a different OOP pattern if needed, although I'd like to stay as close as possible to native ES6 classes.

Aucun commentaire:

Enregistrer un commentaire