關於Javascript的ES6 extends 多重繼承辦法


在對openmodelica的部件基類js重寫時候遇到了多重繼承問題,js本身是不支持多重繼承的。用了以下辦法做了多重繼承

function mix (...mixins) { 
  class Mix { }
  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)
    }
  }
}
// class DistributedEdit extends mix(Loggable, Serializable) { }

直接調用mix()方法就行,例如下面代碼:

// 多邊形
class Polygon extends mix(GraphicItem,FilledShape) {
  constructor(lineColor, fillColor, fillPattern, points) {
    this.lineColor = lineColor;
    this.fillColor = fillColor;
    this.fillPattern = fillPattern;
    this.points = points; //數組字符串
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM