gpt4 book ai didi

javascript - 为什么我的 JS 类之间出现引用错误?

转载 作者:行者123 更新时间:2023-12-01 01:06:20 24 4
gpt4 key购买 nike

我试图从我的 Leaderboard 类中调用在我的 Player 类中声明的 averageScore() 函数,但是我'我收到引用错误。

将我的 Player 类中的代码拖放到控制台中效果很好,但是当我尝试从 Leaderboard 调用它时,我收到一个 Reference error: add_score is未定义

这是我的玩家类别:

class Player {

constructor(player_id, score) {
this.player_id = player_id;
this.scores = [score];
this.total = score;
//this.average = this.total/this.scores.length;
}

addScore(score) {
this.total += score;
this.scores.push(score);
return score;
}

averageScore() {
return this.scores.length ? this.total / this.scores.length : 0;
}

resetScore() {
this.scores = [];
this.score = 0;
}

};

这是我的排行榜类:

class LeaderBoard extends Player {

add_score = (player_id, score) => {
if (!this.player_id) {
var newPlayer = new Player(player_id, score);
this.player_id = newPlayer;
} else {
var average = this.player_id.averageScore();
return average.toFixed(1);
}

};
/*...(additional functions and closing bracket excluded)*/

我预计averageScore会显示为add_score调用它,但我得到了引用错误 - 有什么想法吗?

最佳答案

LeaderBoard 扩展 Player 是没有意义的,因为 LeaderBoard 将包含玩家列表

请参阅下面的代码以获取工作示例

class Player {
constructor(player_id, score) {
this.player_id = player_id;
this.scores = [score];
this.total = score;
//this.average = this.total/this.scores.length;
}

addScore(score) {
this.total += score;
this.scores.push(score);
return score;
}

averageScore() {
return this.scores.length ? this.total / this.scores.length : 0;
}

resetScore() {
this.scores = [];
this.score = 0;
}

};
class LeaderBoard {
constructor() {
this.players = {};
}
addScore(player_id, score) {
if (!this.players[player_id]) {
this.players[player_id] = new Player(player_id, score);
} else {
this.players[player_id].addScore(score);
}
var average = this.players[player_id].averageScore();
return average.toFixed(1);
}
};
let x = new LeaderBoard();
console.log(x.addScore(1, 1)); // avg is 1 / 1 === 1
console.log(x.addScore(1, 3)); // avg is (1 + 3) / 2 === 2
console.log(x.addScore(1, 5)); // avg is (1 + 3 + 5) / 3 === 3
console.log(x.addScore(2, 7)); // avg for player 2 is 7 / 1 === 7

关于javascript - 为什么我的 JS 类之间出现引用错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55603384/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com