The problem of multiple inheritance

  • TypeScript doesn’t support multiple inheritance, which means that a class can only inherit from one class, potentially adding complexity to the program.
  • If, in an environment that supports multiple inheritance, a subclass inherits from two parent classes with the same name, it is unclear or ambiguous which parent class method will be called when the subclass calls the parent class method.
// The following code is an error code
class Bat extends WingeAnimal.Mammal {
    // ...
}
Copy the code

With introduction

  • Sometimes, however, we think it’s a good idea to declare a class that inherits from two or more classes at the same time.
  • To avoid the potential dangers of multiple inheritance implementations, we can use the Mixin feature.
  • The first are the two base classes
class Mammal {
    breathe() : string {
        return "I'm alive!"; }}class WingedAnimal {
    fly() : string {
        return "I can fly!"; }}Copy the code
  • Here are the subclasses, usingimplementsalternativeextends, so the inherited class still needs to be implemented
class Bat implements Mammal.WingedAnimal {
    breathe: () = > string;
    fly: () = > string;
}
Copy the code

Implement/copy methods from the base class into subclasses using the following functions

function applyMixins(derivedCtor: any, baseCtors: any[]) {
    baseCtors.forEach(baseCtor= > {
        // Copy attributes from the "parent" prototype object to the child's prototype object
        Object.getOwnPropertyNames(baseCtor.prototype).forEach(name= > {
            if(name ! = ='constructor') { derivedCtor.prototype[name] = baseCtor.prototype[name]; }}); }); }// Implement subclass functions
applyMixins(bat, [Mammal, WingedAnimal]);
Copy the code

Mixed restriction

  1. Only one-level methods and properties can be inherited from the inheritance tree. Because when compiled, in JavaScript, the methods of the parent class are in the prototype object of the parent class, and the methods of the parent class are not found in the prototype object of the child class.
  2. If two or more parent classes contain methods of the same name, then only the passing in is inheritedapplyMixinsIn the functionbaseCtorThe method in the last class in the array.