Splitting up class definition in ES 6 / Harmony

我的梦境 提交于 2019-12-18 01:16:07

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/27956779/splitting-up-class-definition-in-es-6-harmony

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!