使用单个值在javascript中创建对象数组

时间:2013-08-11 11:22:51

标签: javascript

我的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
});

2 个答案:

答案 0 :(得分:2)

问题是你在很多地方为全局窗口对象赋值,它们会相互覆盖而导致混乱。您需要在本地创建变量来解决此问题。查看修订后的代码,并附上解释已发生变化的评论。

function GameButton(c, i) {
  var color = c; //use var to avoid assigning this variable  to window object
  var id = i; //use var to avoid assigning this variable  to window object
  var markup = '<div class="'+i+'"></div>'; //use var to avoid assigning this variable  to window object

  this.getColor = function () {
    return color;
  };
  this.getMarkup = function () {
    return markup;
  };
}

function GameBoard() {
  //use var to avoid assigning this variable to window object
  var gameButton = new Array();

  //This will declare a local function intead of assigning the function to window object like in your code.
  function addGameButton(color,id) {
    gameButton[gameButton.length] = new GameButton(color,id);
  };

  this.createGameBoard = function (color) {

    var col = color || ["red", "green", "blue"]; //Use default ["red", "green", "blue"] if there is no color passing in
    addButtons(col);
  };

   //This will declare a local function intead of assigning the function to window     object like in your code.
  function addButtons(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(){
  //Declare a local variable.
  var gameBoard = new GameBoard();
  gameBoard.createGameBoard();

  var b = gameBoard.getGameButton(0);
  console.log(b.getColor());

});

答案 1 :(得分:1)

您需要学习使用局部变量。目前coloridmarkup是隐式全局变量,可以从GameButton实例设置和读取。

使用var statement将它们声明为构造函数的本地。