类参数的继承

问题描述 投票:2回答:2

我想使用所有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”。

这是我第一次尝试使用类(制作一个小游戏),我并不完全理解类继承是如何工作的。

javascript class
2个回答
2
投票

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

0
投票

另外,基于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
© www.soinside.com 2019 - 2024. All rights reserved.