15

Suppose I have a class in one big file like this:

export default class {
  constructor () {}
  methodA () {}
  methodB () {}
  methodC () {}
}

And I want to break up the class definition so that methodA, methodB, and methodC are each defined in their own separate files. Is this possible?

0x8890
  • 515
  • 1
  • 4
  • 12

2 Answers2

16

You should be able to, as class is supposed to just be syntax sugar for the usual prototype workflow:

import methodOne from 'methodOne'
import methodTwo from 'methodTwo'

class MyClass {
  constructor() {
  }
}

Object.assign(MyClass.prototype, {methodOne, methodTwo})

export default MyClass
elclanrs
  • 92,861
  • 21
  • 134
  • 171
8

@elclanrs gave a correct answer, but I would modify it to allow for the use of this. I also think this is more readable.

import methodOne from 'methodOne'
import methodTwo from 'methodTwo'

class MyClass {
  constructor() {
    this.methodOne = methodOne.bind(this)
    this.methodTwo = methodTwo.bind(this)
  }
}

export default MyClass

Tip: although if your class is so large that it warrants being split into multiple files, a better solution might be to split up the class into multiple classes.

mikestaub
  • 2,134
  • 4
  • 24
  • 34
  • 2
    elclanrs' answer does allow the use of `this`; the only difference as far as I see is that the functions seem to be enumerable when using your method. This is usually not desired... (compared with nodejs util.inspect with tries on both answers) – LFLFM Apr 05 '19 at 14:07