我的 javascript 代码有问题。我使用了一个循环来执行这个函数几次。
addGameButton = function(color,id) {
gameButton[gameButton.length] = new GameButton(color,id);
};
所以我有一个名为 gameButton 的 GameButton 对象数组。我正在尝试添加新的游戏按钮,每个按钮都有不同的颜色和 ID。但是,所有对象最终都具有相同的值。我认为我将值分配给数组的方式有问题。下面是整个例子。
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
});