我想让 Bob 成为一个具有所有 NPC
类参数和所有 Civil
类参数的 NPC
,但是 我不知道如何声明它,因此两个类都会读取 params
关联数组来定义 Bob 属性。
我的代码:
class Civil {
constructor(params) {
params["gold"] ? this.gold = params["gold"] : this.gold = 0;
}
}
class NPC extends Civil {
constructor(params) {
super();
params["name"] ? this.name = params["name"] : this.name = "No name defined";
params["race"] ? this.race = params["race"] : this.race = "No race defined";
}
}
var bob = new NPC({
"name": "Bob",
"race": "Human",
"gold": 10
});
console.log(bob.name);
//returns that "params" is undefined in Civil class
如果我不在 Civil
类中使用 params
并简单地将 this.gold 设置为 int,则一切正常,并且 Bob.gold 返回 int,Bob .name 返回“Bob”,Bob.race 返回“Human”。
这是我第一次尝试类(制作一个小游戏),我并不完全理解类继承是如何工作的。
最佳答案
将params
传递给super()
。否则,类 Civil
会在没有任何参数的情况下启动,并且无法访问传递给 NPC
的参数。此外,您还可以将 this
变量的赋值缩短一些。
class Civil {
constructor(params) {
if(!params) throw new Error("Params must be set")
this.gold = params["gold"] ? params["gold"] : 0;
}
}
class NPC extends Civil {
constructor(params) {
if(!params) throw new Error("Params must be set")
super(params); // <-- pass them here.
this.name = params["name"] ? params["name"] : "No name defined";
this.race = params["race"] ? params["race"] : "No race defined";
}
}
var bob = new NPC({
"name": "Bob",
"race": "Human",
"gold": 10
});
console.log(bob.name);
//returns that "params" is undefined in Civil class
关于javascript - 类参数的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52354456/