es6实现类的多重继承

1.类的多种继承,将多个类的接口“混入”(mix in)另一个类。

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

2.应用,上面代码的mix函数,可以将多个对象合成为一个类。使用的时候,只要继承这个类即可。

class Lottery extends mix(Base, Calculate, Interface, Timer){
  //...  
}

3.参考

http://es6.ruanyifeng.com/#docs/class-extends

 

posted @ 2019-04-11 21:10  小方块的世界  阅读(2917)  评论(0编辑  收藏  举报