I have a problem with my javascript code. I use a loop which executes this function a couple of times.
addGameButton = function(color,id) {
gameButton[gameButton.length] = new GameButton(color,id);
};
So I have an array of GameButton objects called gameButton. I am trying to add new gamebuttons which each have a different color and id. However, all the objects end up having the same values. I assume there's something wrong they way I am assigning values to array. Below is the whole example.
function GameButton(c, i) {
color = c;
id = i;
markup = '<div class="'+i+'"></div>';
this.getColor = function () {
return color;
};
this.getMarkup = function () {
return markup;
};
}
function GameBoard() {
gameButton = new Array();
addGameButton = function(color,id) {
gameButton[gameButton.length] = new GameButton(color,id);
};
this.createGameBoard = function (color) {
color = ["red", "green", "blue"];
addButtons(color);
};
addButtons = function (color) {
var i = 0;
for (i=0; i <color.length; i++) {
addGameButton(color[i],i);
}
};
this.getGameButton = function (index) {
return gameButton[index];
};
}
$(document).ready(function(){
gameBoard = new GameBoard();
gameBoard.createGameBoard();
b = gameBoard.getGameButton(0);
console.log(b.getColor());
// returns blue instead of red, also getGameButton(1) has the same values
});
gameButton.length?gameButton[] = new GameButton(color,id);gameButton[gameButton.length] = new GameButton(color,id);togameButton.push(new GameButton(color,id));gameButton()does not use color at all.