0

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

2 回答 2

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());

});
于 2013-08-11T11:42:09.380 回答
1

您需要学习使用局部变量。目前color,id和是从任何实例markup中设置和读取的隐式全局变量。GameButton

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

于 2013-08-11T11:27:53.170 回答