gpt4 book ai didi

javascript - 是否可以从父类访问子类的属性?

转载 作者:搜寻专家 更新时间:2023-10-30 21:24:42 25 4
gpt4 key购买 nike

我有一个父类,我在其中定义商店关系函数,还有一个子类在商店中定义其表。在父类中,我定义了一个 save()连接到实例表的函数,但该表是在子实例上定义的。我想我可以设置父级的构造函数来接受子级的 tableName ,但我的 linter 提示 super必须在我引用 this 之前调用(即使我想将 this 上的属性传递给 super )。

这是父级:

export class StoredObject {
constructor(private tableName: string) {}

public save() {
store.collection(this.tableName) //...
}
}

还有 child :

export class Inventory extends StoredObject {
tableName = "inventory";

constructor(
public myVar //...
) {
super(this.tableName)
}
}

我知道一个解决方案是创建一个只返回 this.tableName 值的 getter 函数,但这似乎很老套。我也知道我可以简单地将实际字符串放在 super 中(例如,在 Inventory 中,构造函数为 { super("inventory") } ,但这似乎不够优雅。我怀疑有一种方法可以按惯例实现我想要做的事情,但我似乎找不到它。

最佳答案

看看Ryan Cavanaugh's response here

具体而言,

The order of initialization is:

  1. The base class initialized properties are initialized
  2. The base class constructor runs
  3. The derived class initialized properties are initialized
  4. The derived class constructor runs

您已经让您的父类(super class)负责初始化 tableName 属性,并且它必须能够在创建您的子类之前完成这项工作。您要么必须传递“库存”,要么改变这种关系。

关于javascript - 是否可以从父类访问子类的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37287207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com