【问题标题】:Splitting up class definition in ES 6 / Harmony在 ES 6 / Harmony 中拆分类定义
【发布时间】:2015-03-13 10:53:01
【问题描述】:

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

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

我想分解类定义,以便 methodAmethodBmethodC 分别定义在各自单独的文件中。这可能吗?

【问题讨论】:

    标签: javascript ecmascript-6 ecmascript-harmony


    【解决方案1】:

    @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
    

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

    【讨论】:

    • elclanrs 的回答确实允许使用this;据我所知,唯一的区别是使用您的方法时这些函数似乎是可枚举的。这通常是不希望的......(与 nodejs util.inspect 相比,尝试两个答案)
    【解决方案2】:

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

    import methodOne from 'methodOne'
    import methodTwo from 'methodTwo'
    
    class MyClass {
      constructor() {
      }
    }
    
    Object.assign(MyClass.prototype, {methodOne, methodTwo})
    
    export default MyClass
    

    【讨论】:

    • 但是如果我想要有属性的方法呢?方法一(a,b)
    • methodOnemethodTwo怎么用?
    猜你喜欢
    • 1970-01-01
    • 2016-12-22
    • 2017-10-24
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 2016-11-02
    相关资源
    最近更新 更多