The problem arises:
The inheritance chain is as follows:
My Dog
object implements the Animal
properties of the class, but I also want to inherit the Friendly
class. Get sharing attributes.
problem solved
In fact, ES6 classes cannot implement multiple inheritance. I cannot achieve multiple inheritance in this form: I
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. Dog
The declaration of the class is easily realized :
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 prototype
again, no deep copy was performed, that is Friendly
, if the class has an upper parent class, it Dog
cannot be inherited, and I will take the time to modify the function.