ES6 模式下的多继承实现

问题产生:

继承链如下:

在这里插入图片描述
我的Dog对象实现了Animal类的属性,但是我同时想继承Friendly类。获取分享属性。

问题解决

实际上ES6的 class并不能实现多继承。我无法通过这种形式实现多继承:
在这里插入图片描述
网上找了许多mixmin的思路和想法,最终在阮一峰老师的博客内找到了解决方案:

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);
    }
  }
}

通过上述继承代码。轻松的实现了Dog类的声明:

在这里插入图片描述
经过测试,继承链,属性链,方法链均正常。仅有一个问题,super()函数调用父类时,无法传递参数。修改阮老师上面的代码如下:

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

测试。一切正常


后续补充:

实际使用中,发现mix函数再复制原型链prototype的时候,并没有进行深度拷贝,即Friendly类若有上层父类,则Dog无法继承,函数我会抽空进行修改。

猜你喜欢

转载自blog.csdn.net/qq_29722281/article/details/96979042