javascriptclassextendses6-class

How can I conditionally choose a base class for my subclass?


Here is the thing. I have a main class called A. I want this class to extend class B.

class A extends B {}

But in fact, I want the class B to extend C, D or E on a specific condition:

class B extends B1 {}

or

class B extends B2 {}

or

class B extends B3 {}

So the B class would be a "fake" class, just to check a condition and then extend the right class. In the final, the result would be the same as:

class A extends B1 {}

or

class A extends B2 {}

or

class A extends B3 {}

I know this is possible in PHP, with abstract classes or wrapper classes for example. But how to do that in JavaScript ES6?

Thanks


Solution

  • So classes in javascript are really not setup in the same classical inheritance way as other languages, the best way to do what you want is to set the prototype of the object you are dealing with. There are a few ways.

    Object.setPrototypeOf(currentObj, newPrototype);
    

    Where newPrototype is the object you are wanting to inherit from. Here are a couple good articles on it if you want to learn the inner workings.

    http://yehudakatz.com/2011/08/12/understanding-prototypes-in-javascript/

    https://github.com/getify/You-Dont-Know-JS/blob/master/this%20%26%20object%20prototypes/ch5.md