假设我有一个类在一个大文件中,就像这样:
export default class {
constructor () {}
methodA () {}
methodB () {}
methodC () {}
}
我希望将类定义拆分成单独的文件,使得methodA
、methodB
和methodC
各自定义在不同的文件中。这种做法可行吗?
假设我有一个类在一个大文件中,就像这样:
export default class {
constructor () {}
methodA () {}
methodB () {}
methodC () {}
}
我希望将类定义拆分成单独的文件,使得methodA
、methodB
和methodC
各自定义在不同的文件中。这种做法可行吗?
你应该可以这样做,因为class
只是通常原型工作流的语法糖:
import methodOne from 'methodOne'
import methodTwo from 'methodTwo'
class MyClass {
constructor() {
}
}
Object.assign(MyClass.prototype, {methodOne, methodTwo})
export default MyClass
@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
提示:尽管如果您的类非常庞大,需要分成多个文件,但更好的解决方案可能是将类拆分为多个类。
this
关键字;据我所知,与你的方法相比,唯一的区别似乎是使用该方法时函数似乎可枚举。通常这不是期望的...(与Node.js util.inspect进行比较并尝试两个答案) - LFLFM
methodOne
如何使用methodTwo
? - GeminiYellowfunction methodOne() { this.methodTwo() }
- Bergi