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