Javascript 函数,多原型继承

Javascript functions, multiple prototype inheritance

我有一项任务是使用 javascript 原型和构造函数来实现图表。 现在我必须使用原型来实现多重继承。我知道如何实现单一继承,但我坚持继承多个原型。

这个问题的重点是 WeatherData 继承 EventDataType 对象。

import { DataType, Event } from "./../common/EventData.mjs"

export function WeatherData(value, { time, place }, { type, unit, isInternational }) {
    Event.call(time, place)
    DataType.call(type, unit, isInternational)
    this.value = value
}

WeatherData.setPrototypeOf(WeatherData.prototype, Event.prototype)
WeatherData.setPrototypeOf(WeatherData.prototype, DataType.prototype)

WeatherData.prototype.getValue = function () { return this.value }

我还没有测试代码,但我确定它是错误的,因为第二个 .setPrototypeOf() 覆盖了第一个函数,这意味着 WeatherData 的原型将是 DataType

我已经在互联网上搜索过,但找不到答案,可能是因为这种方法已经过时了。

可以像这样对 OP 的代码进行多继承粘合代码的重构尝试...

import { DataType, Event } from "./../common/EventData.mjs"

function WeatherData(
  value,
  { time, place },
  { type, unit, isInternational }
) {
  // - close to an instance level super call but done twice.
  //
  // - technically applying two function based mixins.
  Event.call(this, time, place);
  DataType.call(this, type, unit, isInternational)

  this.value = value
}
// - prototype level kind of multiple superclass extension.
//
// - technically mixed-in prototype objects via
//   `Object.assign`
WeatherData.prototype = Object.assign(

  // ... aggregate a compound prototype.
  {},
  Event.prototype,
  DataType.prototype,
);

// prevent latest mixed-in super-constructor, here
// `DataType`, from being the sub-classed constructor.
WeatherData.prototype.constructor = WeatherData;

WeatherData.prototype.getValue = function () {
  return this.value;
}

export/* default*/ WeatherData;

上面的构造函数实现覆盖了instance/object级别的mixin部分。从两个其他原型对象聚合和分配原型复合的代码是最接近 JS 中可用的多重继承的代码。

但是上述代码的设计也存在缺陷,因为这样的复合原型确实会失去与 EventDataType 的任何可能可用原型链的任何进一步链接。

因此,从建模的角度来看,如果可用的代码库是以一种可以让 WeatherDataDataType 继承的方式提供的,而 Event 的原型不可知实现则更好可以另外应用为基于函数的 mixin。