Implementation of multiple inheritance in ES6 mode

The problem arises:

The inheritance chain is as follows:

Insert picture description here
My Dogobject implements the Animalproperties of the class, but I also want to inherit the Friendlyclass. Get sharing attributes.

problem solved

In fact, ES6 classes cannot implement multiple inheritance. I cannot achieve multiple inheritance in this form: I
Insert picture description here
found many mixmin ideas and ideas on the Internet , and finally found a solution in the blog of teacher Ruan Yifeng :

function mix(...mixins) {
  class Mix {
    constructor() {
      for (let mixin of mixins) {
        copyProperties(this, new mixin()); // 拷贝实例属性
      }
    }
  }

  for (let mixin of mixins) {
    copyProperties(Mix, mixin); // 拷贝静态属性
    copyProperties(Mix.prototype, mixin.prototype); // 拷贝原型属性
  }

  return Mix;
}

function copyProperties(target, source) {
  for (let key of Reflect.ownKeys(source)) {
    if ( key !== 'constructor'
      && key !== 'prototype'
      && key !== 'name'
    ) {
      let desc = Object.getOwnPropertyDescriptor(source, key);
      Object.defineProperty(target, key, desc);
    }
  }
}

Inherit the code through the above. DogThe declaration of the class is easily realized :

Insert picture description here
After testing, the inheritance chain, attribute chain, and method chain are all normal. There is only one problem. When the super() function calls the parent class, it cannot pass parameters. Modify the above code of Mr. Ruan as follows:

  class Mix {
    constructor(...ags) {
      for (let mixin of mixins) {
        copyProperties(this, new mixin(ags)); // 拷贝实例属性
      }
    }
  }

test. everything is normal


Follow-up supplement:

In actual use, I found that when the mix function copied the prototype chain prototypeagain, no deep copy was performed, that is Friendly, if the class has an upper parent class, it Dogcannot be inherited, and I will take the time to modify the function.

Guess you like

Origin blog.csdn.net/qq_29722281/article/details/96979042