在子类中调用rnd.winner()
时,我得到未定义的值。这应该像JOHN一样从父级返回玩家的名字。从子项调用测试函数会从父项返回正确的值win()
。调用super.constructor.name
作为返回状态返回父母班级名称 - >player
现在为什么?在访问父构造函数时,JS类子类返回undefined
class player {
constructor(name) {
this.name = name;
this.win = 0;
this.loss = 0;
};
win() {
return this.win;
};
loss() {
return this.loss;
};
};
class scoreBoard extends player {
constructor(round) {
super();
this.round = round;
this.emblem = 0;
};
add() {
return this.round.push([...this.round].pop() + 1);
}
winner() {
return super.name;
};
loser() {
return super.constructor.name;
};
emblem() {
return this.emblem;
};
test() {
return super.win();
};
};
let plr = new player("JOHN"),
rnd = new scoreBoard([0]);
console.log(plr.name, rnd.winner(), rnd.test());
不要在普通数据属性中使用'super'。它们始终存在于您当前的实例中。改用'this.name'。 – Bergi
为什么你觉得'scoreBoard'是'player'的扩展?我没有真正理解逻辑。对于记分牌(有赢家和输家的方法),你至少需要两名玩家,所以我不会在继承关系中获得你所希望的。为什么“围绕”一个数组? 'constructor.name'对你的'name'属性有*无关。它是函数的预定义属性(因为'constructor'是一个函数)。 – trincot