我想使用所有NPC
类参数和所有NPC
类参数使Bob成为Civil
,但我不知道如何声明它,因此两个类都读取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
如果我不在params
类中使用Civil
并简单地将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
另外,基于Luca Kiebel's answer(在super
调用中缺少参数)和Michelangelo's comment(在构造函数中使用默认参数),我会像这样重写:
class Civil {
constructor(params = { "gold": 0 }) {
this.gold = params["gold"];
}
}
class NPC extends Civil {
constructor(params = { name: "No name", race: "No race" } ) {
super(params);
this.name = params["name"];
this.race = params["race"];
}
}
var bob = new NPC({
"name": "Bob",
"race": "Human",
"gold": 10
});
console.log("Name (NPC with custom params): " + bob.name); // Ok
bob = new NPC();
console.log("Name (NPC with default params): " + bob.name); // Ok, no error
如果您不检查params存在/有效性,您可能会收到错误:
“message”:“未捕获的TypeError:无法读取未定义的属性'gold'”
class Civil {
constructor(params) {
this.gold = params["gold"] ? params["gold"] : 0; // <-- missing check "params" exists
}
}
class NPC extends Civil {
constructor(params) {
super(params);
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("Name (NPC with custom params): " + bob.name); // Ok
bob = new NPC();
console.log("Name (NPC with default params): " + bob.name); // Error: Uncaught TypeError: Cannot read property 'gold' of undefined
// in NDC constructor