Split a Javascript class (ES6) over multiple files?

ecmascript-6, javascript

Solution

When you create a class

class Foo extends Bar {
  constructor(a, b) {
  }
}

you can later add methods to this class by assigning to its prototype:

// methodA(a, b) in class Foo
Foo.prototype.methodA = function(a, b) {
  // do whatever...
}

You can also add static methods similarly by assigning directly to the class:

// static staticMethod(a, b) in class Foo
Foo.staticMethod = function(a, b) {
  // do whatever...
}

You can put these functions in different files, as long as they run after the class has been declared.

However, the constructor must always be part of the class declaration (you cannot move that to another file). Also, you need to make sure that the files where the class methods are defined are run before they are used.

Problem

I have a JavaScript class (in ES6) that is getting quite long. To organize it better I'd like to split it over 2 or 3 different files. How can I do that? Currently it looks like this in a single file: ``` class foo extends bar { constructor(a, b) {} // Put in file 1 methodA(a, b) {} // Put in file 1 methodB(a, b) {} // Put in file 2 methodC(a, b) {} // Put in file 2 } ```

Original source

Related problems