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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM