Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting up class definition in ES 6 / Harmony

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?

like image 890
0x8890 Avatar asked Jan 15 '15 04:01

0x8890


2 Answers

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
like image 194
elclanrs Avatar answered Oct 31 '22 12:10

elclanrs


@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.

like image 20
mikestaub Avatar answered Oct 31 '22 13:10

mikestaub