您好,我有一个问题,如何在另一个类中引用一个类的数组
我有类(class)队列和类(class)球员 队列中将有一群玩家
类(class)玩家:
class Player {
constructor(id, name) {
this.id = id;
this.name = name;
}
}
module.exports = Player;
类队列
const Match = require('./Match');
// Queue class is a queue system with players.
class Queue {
constructor() {
this.players = [];
}
// addPlayers add multiple players into queue
addPlayers(players) {
this.players = this.players.concat(players);
}
// addPlayer adds a single player into queue
addPlayer(player) {
this.players.push(player);
}
// removePlayers remove multiple players from queue
removePlayers(players) {
players.forEach(p => {
this.removePlayer(p);
});
}
// removePlayer removes a single player from queue
removePlayer(player) {
const index = this.players.findIndex(p => p.id === player.id);
if (index > -1) {
this.players.splice(index, -1);
}
}
// getPlayers return players that are currently on queue
getPlayers() {
return this.players;
}
// makeMatch makes match with provided condition and removes
// matching players from queue
makeMatch(condition) {
// make matched players
const matchedPlayers = this.players.filter(condition);
console.log(matchedPlayers);
// remove matched players from this.players
this.removePlayers(matchedPlayers);
// return new Match with matched players
return new Match(matchedPlayers);
}
}
module.exports = Queue;
或者没有必要在另一个类中引用这个类。
最佳答案
在普通的 JavaScript 中,数组可以保存任何类型的对象,因此无需引用 Player 类。如果需要,您可以使用 instanceof
( https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof ) 检查对象的实例类型,即用于创建对象的构造函数。例如。在你的 addPlayer 中:
addPlayer(player) {
if(player instanceof Player) {
this.players.push(player);
} else {
throw new Error('Only players can be added to the queue')
}
}
关于JavaScript 类引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59023026/