javascript - 如何在javascript中扩展父类的实例变量
问题描述
我正在尝试扩展父类的实例变量,但流 js 抱怨这是不正确的。有什么我想念的吗?
// BaseClass
export type AdType = {
dom: HTMLElement,
};
export default class AdsRefresh {
ads: AdType[] = [];
constructor(configs) {
this.ads = configs;
}
}
// ChildClass
import type {AdType as BaseAdType, PlaceholderType} from './adsRefresh';
export type AdType = {
placeholderIndex?: number
} & BaseAdType;
class AdsRefreshTiler extends AdsRefresh {
ads: AdType[] = [];
constructor(configs) {
super(configs);
this.ads = this.getAds(configs);
}
}
Cannot extend `AdsRefresh` [1] with `AdsRefreshTiler` because property `placeholderIndex` is missing in `AdType` [2] but exists in object type [3] in property `ads`.Flow(InferError)
解决方案
看起来 Flow 不支持覆盖类型,并且抱怨父级和子级中“广告”字段的类型冲突。不允许您更改在子级中的父级中定义的字段的类型。
这样才能维持子父关系。如果您更改子类中某个字段的类型,则当您在子类上调用它们时,您在父类中定义的函数可能不再起作用。
例如
export default class Parent {
felid1: number;
parentFunction() {
return this.felid1 / 3;
}
}
class Child extends Parent {
field1: string; // Now the parentFunction wont work since you can't divide strings
}
var a = new Parent();
a.felid1 = 1;
a.parentFunction(); // Does not crash
var c = new Child();
c.field1 = "a";
c.parentFunction(); // Crashes
你必须重组你的对象,这样就不会发生这种情况。通过将广告分解为多个字段或不使用扩展。
推荐阅读
- php - PHP基于“新”数据更新多行
- javascript - 在javascript中用分隔符分割字符串?
- javascript - 如何知道文件下载的进度
- modelica - 关闭卷 - 初始化错误 - Modelica
- node.js - 如何在 https 客户端的服务器上显示图像?
- wpf - 选择行时将可编辑的 DataGridCells 切换到编辑模式?
- javascript - 提取对象属性作为名称
- javascript - 如何在 JavaScript 中过滤未知数量的数组值?
- javascript - 悬停父项时触发子项的悬停状态 - 有可能吗?
- python - KeyError:“['...'] 不在索引中”可能的全局/实例变量混淆