如何用一个class扩展多个classes(不是多重继承)?

How to use one class to extend multiple classes (not multiple inheritance)?

这里有几个 JS classes。 GrandChildOneGrandChildTwo class 是相同的,但扩展了不同的父 class。由于他们的代码相同,我正在寻找摆脱这种重复的方法。换句话说,我想要一个 class(我们称它为 GrandChild)并用它来扩展 ChildOneChildTwo classes。有什么建议吗?

class Parent {
  someParentMethod () {
     console.log('Parent')
  }
}

class ChildOne extends Parent {
   someChildOneMethod () {
     console.log('someChildOneMethod')
  }
}

class ChildTwo extends Parent {
   someChildTwoMethod () {
     console.log('someChildTwoMethod')
   }
}


// THE CLASSES BELOW ARE IDENTICAL
class GrandChildOne extends ChildOne {
   someGrandChildMethod() {
     console.log('someGrandChildMethod')
   }
}
class GrandChildTwo extends ChildTwo {
   someGrandChildMethod() {
     console.log('someGrandChildMethod')
   }
}

const grandChildOne = new GrandChildOne()
const grandChildTwo = new GrandChildTwo()

您可以为此使用 Mix-ins (example in MDN)

会是这样的:

class Parent {
  someParentMethod () {
     console.log('Parent')
  }
}

class ChildOne extends Parent {
   someChildOneMethod () {
     console.log('someChildOneMethod')
  }
}

class ChildTwo extends Parent {
   someChildTwoMethod () {
     console.log('someChildTwoMethod')
   }
}


// define GrandChild as a Mix-in:
let GrandChild = Base => class extends Base {
  someGrandChildMethod() {
     console.log('someGrandChildMethod')
   }
};

//Then:
class GrandChildOne extends GrandChild(ChildOne) { }
class GrandChildTwo extends GrandChild(ChildTwo) { }

const grandChildOne = new GrandChildOne()
const grandChildTwo = new GrandChildTwo()

grandChildOne.someChildOneMethod();
grandChildTwo.someChildTwoMethod();