将ES6 / Harmony中的类定义拆分

15

假设我有一个类在一个大文件中,就像这样:

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

我希望将类定义拆分成单独的文件,使得methodAmethodBmethodC各自定义在不同的文件中。这种做法可行吗?

2个回答

16

你应该可以这样做,因为class只是通常原型工作流的语法糖:

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

class MyClass {
  constructor() {
  }
}

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

export default MyClass

1
但是如果我想要具有属性的方法呢?methodOne(a,b) - marschro
methodOne 如何使用 methodTwo - GeminiYellow
@GeminiYellow 一如既往,function methodOne() { this.methodTwo() } - Bergi

8

@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

提示:尽管如果您的类非常庞大,需要分成多个文件,但更好的解决方案可能是将类拆分为多个类。


2
elclanrs的回答允许使用this关键字;据我所知,与你的方法相比,唯一的区别似乎是使用该方法时函数似乎可枚举。通常这不是期望的...(与Node.js util.inspect进行比较并尝试两个答案) - LFLFM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接