我现在对此非常困惑,如何获得父类构造函数的参数?我想获取狮子的DNA,然后将其传递给小狮子并使用它。请注意,这并不是我个人使用的,而是包/模块,因此我无法输入在代码中输入的内容。
示例代码:
class Lion {
constructor(client, DNA = {}) {
this.sharp = howsharp;
this.client = client;
}
}
class BabyLion extends Lion {
constructor(client) {
super(client, How can I get DNA??);
}
}
我尝试过的事情:
super(client)
和super(client, {somestuff})
-显然不起作用,因为我正在跟踪事先声明的Lion的DNA。let dna
然后执行dna = DNA
然后导出它-“显然”是行不通的。答案 0 :(得分:1)
您无需“获取父级的参数”,需要在覆盖的构造函数中定义所有必需的参数,然后将其传递给super()
:
class BabyLion extends Lion {
constructor(client, DNA) {
super(client, DNA);
}
}
您可以向BabyLion
的{{1}}添加更多的参数,也可以更少,但是您孩子的构造函数需要以某种方式获取所有必需的参数并将其传递给父母的构造函数。例如:
constructor
答案 1 :(得分:0)
class Lion {
constructor(sharp, client) {
this.sharp = sharp
this.client = client;
}
getSharp(){
return this.sharp;
}
}
class BabyLion extends Lion {
constructor(sharp, client) { // Here you can use more BabyLion parameters
super(sharp, client);
}
}
a = new BabyLion(1, 2)
a.getSharp(); // returns ==> 1. This way it gets other attribures from Lion class
答案 2 :(得分:0)
如果有帮助。
class Lion {
constructor(client, DNA = {}) {
this.sharp = 'howsharp';
this.client = client;
this.dna = DNA;
}
}
class BabyLion extends Lion {
constructor(client) {
super(client);
}
printDna() {
console.log(this.dna);
}
}
var baby = new BabyLion('hoper');
baby.printDna();
答案 3 :(得分:0)
目前尚不清楚您想做什么。但是,如果您想模仿父母->儿童继承,则可以执行以下操作:
const mix = (dna1, dna2) => Object.keys(dna1).reduce(
(strand, key) => Object.assign(strand, {[key]: Math.random() < .5
? dna1[key]
: dna2[key]
}), {}
)
class Lion {
constructor(name, DNA = {}) {
this.name = name
this.DNA = DNA;
}
mate(partner, name) {
return new Lion(name, mix(this.DNA, partner.DNA))
}
}
const father = new Lion('Mufasa', {foo: 1, bar: 2, baz: 3, qux: 4})
const mother = new Lion('Surabi', {foo: 5, bar: 6, baz: 7, qux: 8})
const child = mother.mate(father, 'Simba')
console.log(child)
这不使用软件中使用的继承。 (一头小狮子仍然只是另一头狮子。)但是,这只(确实)从每个父母那里继承了它的基因。
我假设这与您真正想要的没有任何关系。但是,如果这只是一个虚拟的例子,请当心不要从字面上考虑继承。真实世界的继承与编程概念之间确实存在差异。