关于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