gpt4 book ai didi

typescript :从父类获取扩展类的属性

转载 作者:行者123 更新时间:2023-12-05 08:07:17 36 4
gpt4 key购买 nike

如何在抽象类的方法中获取子类的属性?

abstract class Parent {
id: string;

logProps() {
// HOW can I log all properties of a child class
// and their values? For example, the name.
}
}

class Child extends Parent {
name: string;

constructor(name) {
super();
this.name = name;
}
}

const child = new Child("Daniel");
child.logProps();

最佳答案

我已经稍微改进了你的代码,你错过的是缺少 super(),这表明子类继承了其父类的所有属性。父类中的属性也需要标记为抽象的,或者它们需要在父类中实现。

abstract class Parent {
abstract id: string;

abstract logProps(): Parent; // make abstract or implement here
}

class Child extends Parent {
id: string;
name: string;

constructor(name: string) {
super();
this.id = ""//some initial value
this.name = name;
}

logProps(): Parent {
return this;
}
}

const child = new Child("Daniel");
child.logProps();

我选择将所有属性抽象化,您也可以删除 abstract 关键字并在父类中实现该方法。

编辑

我有另一个实现,你可以在父类中定义方法并简单地记录 this,这将包含所有属性。

abstract class Parent {

id: string = "DEFAULT VALUE";

logProps() {
console.log(this); // Using this, this contains all properties
}
}

class Child extends Parent {

name: string;

constructor(name: string) {
super();
this.name = name;
}
}

const child = new Child("Daniel");
child.logProps();

关于 typescript :从父类获取扩展类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55258993/

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