0x8*_*890 10 javascript ecmascript-harmony ecmascript-6
假设我在一个大文件中有一个类,如下所示:
export default class {
constructor () {}
methodA () {}
methodB () {}
methodC () {}
}
Run Code Online (Sandbox Code Playgroud)
我想分手类的定义,这样methodA,methodB和methodC分别在自己单独的文件中定义.这可能吗?
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)
@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)
提示:虽然如果您的类太大以至于需要拆分为多个文件,但更好的解决方案可能是将类拆分为多个类。
| 归档时间: |
|
| 查看次数: |
1626 次 |
| 最近记录: |