2014-02-08 229 views
0

這是一個非常簡單的面向對象的JavaScript遊戲的開始。我無法將玩家添加到Games players []陣列中。如何才能做到這一點?OO Javascript遊戲,如何添加玩家遊戲的玩家數組?

我已經刪除所有的問題

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

use Array.prototyspe.push();正如你已經做的那樣。你現在的代碼有什麼問題?唯一的問題是,你正在命名一個變量('Player'),就像你已經命名一個類一樣。 –

回答

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; 

順便說一句,我建議你不要調用的參數addPlayerPlayer」,因爲這會隱藏已定義的功能Player。您可能想將其重命名爲「player」。