3

I am trying to break apart a very large JavaScript file. In this file, we have a hierarchy of classes, with many children of the root class. However, the root class has a function with a switch statement that returns a different object of one of its subclasses based on the argument. It looks like this:

class RootClass {
  static FromArg(arg) {
    switch (arg.Type) {
      case FirstType:
        return new FirstSubclass()
      case SecondType:
        return new SecondSubclass()
      ...
    }
  }
}

I kept the subclasses in other JavaScript files. They look like this:

class FirstSubclass extends RootClass {
  ...
}

When they were kept in a single JS file, this worked fine, because everything was defined in one file. However, when I try to break this apart and reference both JS files externally, I run into an issue. I can't load the JS file with the root class first because now the subclasses aren't defined. I also can't load the JS file with the subclasses first because then the root class they're inheriting from isn't defined. Is there a trick to load both of these files into an html page as if they were still in a single JavaScript file?

Edit: This question doesn't solve my problem because I am not trying to export a JS file to another JS file, but I'm looking for a way to load multiple JS files into an HTML file as if they were in one page.

EZAlex
  • 33
  • 4

1 Answers1

1

consider separating your factory pattern from the root class. something like this:

class RootClassFactory {
    static ObjectFromArg(arg) {
        switch (arg.Type) {
            case FirstType:
                return new FirstSubclass()
            case SecondType:
                return new SecondSubclass()
            ...
        }
    }
}

class RootClass {

}

class FirstSubclass extends RootClass {
  ...
}

then just load in order of dependency, with the factory class last.

https://en.wikipedia.org/wiki/Factory_method_pattern

dqhendricks
  • 19,030
  • 11
  • 50
  • 83