0

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

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()
4

1 回答 1

3

您可以为此使用 Mix-ins(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();

于 2020-07-07T15:27:55.000 回答