这是一个非常简单的面向对象的javascript游戏的开始。我无法将玩家添加到Games player []数组中。怎么办呢?
我删除了与问题无关的所有代码
var BobsGame = function(){
this.Players = [];
}
BobsGame.prototype.addPlayer = function(Player){
//not working
Player.Game = this;
this.Players.push(Player);
Player.setId = function(this.Players.length) {
return this.Players.length;
}
return this;
}
var Player = function(name){
this.Game = null;
this.score = 0;
this.name = name;
this.id = null;
// return alert('Player ' + this.name + ' has been created');
}
var myGame = new BobsGame();
var Player1 = new Player("Tom");
var Player2 = new Player("Bob");
myGame.addPlayer(Player1);
答案 0 :(得分:4)
我认为你在尝试:
var BobsGame = function () {
this.Players = [];
};
BobsGame.prototype.addPlayer = function (Player) {
this.Players.push(Player);
Player.id = this.Players.length;
return this;
};
var Player = function (name) {
this.score = 0;
this.name = name;
this.id = null;
// return alert('Player ' + this.name + ' has been created');
};
var myGame = new BobsGame();
var Player1 = new Player("Tom");
var Player2 = new Player("Bob");
myGame.addPlayer(Player1);
错误在以下代码中:
Player.setId = function(this.Players.length) {
return this.Players.length;
}
在这里,您尝试创建一个名为setId
的函数,但不能将this.Players.length
定义为参数。因此,假设您尝试将播放器的ID设置为播放器阵列的长度,您可以像这样简单地分配:
Player.id = this.Players.length;
顺便说一下,我建议您不要调用addPlayer
“Player
”的参数,因为这会隐藏已定义的函数Player
。您可能希望将其重命名为“player
”。