Split a Javascript class (ES6) over multiple files?

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.

Leave a Comment