Splitting up class definition in ES 6 / Harmony

后端 未结 2 2013
独厮守ぢ
独厮守ぢ 2020-12-14 21:53

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

export default class {
  constructor () {}
  methodA () {}
  methodB () {}
  methodC () {}
}
相关标签:
2条回答
  • 2020-12-14 22:08

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

    0 讨论(0)
  • 2020-12-14 22:27

    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
    
    0 讨论(0)
提交回复
热议问题