Home > Software design >  JS: How to create child class from a parent class in Javascript?
JS: How to create child class from a parent class in Javascript?

Time:01-18

How to avoid circular references at the same time create some child classes from the parent class? And keep the constrain that each class need to reside in a different file.

//Parent.mjs:
import Sub from "/.Sub.mjs"
export default class Parent {
    static createSomething(){
        new Sub();
    }
}


//Sub.mjs:
import Parent from "/.Parent.mjs"
export default class Sub extends Parent {
    contructor(){}
}

This question was originally posted here. But there is no solution under that question. If I really want to create a subclass from the superclass what code should I write?

CodePudding user response:

The parent class should not need to know anything about subclass(es).

I don't see why the parent class would need a static method for creating a subclass, but if you feel you really, really need that, then extend the Parent class object from within the Sub.mjs file:

Parent.mjs:

export default class Parent {
}

Sub.mjs:

import Parent from "/.Parent.mjs"
Parent.createSomething = function () {
    return new Sub();
}
export default class Sub extends Parent {
    constructor(){} // fixed typo here
}

Still, I think it is a bad idea to define such a function on the parent class. This looks like an XY problem. The original reason that made you look for such a function in the first place, certainly has a better way to be solved that doesn't involve a parent class that needs to know about a subclass.

  • Related