在ES 6/Harmony中拆分类定义

0x8*_*890 10 javascript ecmascript-harmony ecmascript-6

假设我在一个大文件中有一个类,如下所示:

export default class {
  constructor () {}
  methodA () {}
  methodB () {}
  methodC () {}
}
Run Code Online (Sandbox Code Playgroud)

我想分手类的定义,这样methodA,methodBmethodC分别在自己单独的文件中定义.这可能吗?

elc*_*nrs 10

你应该能够,因为class它应该只是通常原型工作流程的语法糖:

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

class MyClass {
  constructor() {
  }
}

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

export default MyClass
Run Code Online (Sandbox Code Playgroud)


mik*_*aub 6

@elclanrs 给出了正确答案,但我会修改它以允许使用this. 我也认为这更具可读性。

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

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

export default MyClass
Run Code Online (Sandbox Code Playgroud)

提示:虽然如果您的类太大以至于需要拆分为多个文件,但更好的解决方案可能是将类拆分为多个类。

  • elclanrs 的答案确实允许使用“this”;据我所知,唯一的区别是使用您的方法时这些函数似乎是可枚举的。这通常是不需要的...(与 nodejs util.inspect 相比,尝试了两个答案) (2认同)