【问题标题】:How to extend a parent class' instance variable in javascript如何在javascript中扩展父类的实例变量
【发布时间】:2020-04-09 08:38:11
【问题描述】:

我正在尝试扩展父类的实例变量,但 flow 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)

【问题讨论】:

    标签: javascript ecmascript-6 flowtype


    【解决方案1】:

    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
    

    你必须重组你的对象,这样就不会发生这种情况。通过将广告分解为多个字段或不使用扩展。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-19
      • 1970-01-01
      • 2013-04-18
      • 2021-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多