【问题标题】:Javascript functions, multiple prototype inheritanceJavascript函数,多原型继承
【发布时间】:2021-11-14 00:36:14
【问题描述】:

我有一个使用 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

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

【问题讨论】:

标签: javascript inheritance javascript-objects prototype


【解决方案1】:

可以给 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;

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

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

因此,从建模的角度来看,如果可用代码库以一种可以让WeatherData 继承自DataType 的方式提供,而Event 的原型不可知实现可以另外作为基于函数的mixin 应用,那就更好了.

【讨论】:

    猜你喜欢
    • 2014-05-08
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 2010-09-28
    • 2018-02-21
    • 1970-01-01
    相关资源
    最近更新 更多