1

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?

1
  • The superclass shouldn't need to know anything about a subclass. That is a code smell. Commented Jan 17, 2023 at 10:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.