获取所有实例化的javascript对象并更新值

时间:2012-03-28 02:06:42

标签: javascript prototype

这是我拥有的对象的简化示例。我想要做的是当我调用更新方法时,它会根据所有对象进行更新。所以,我需要以某种方式跟踪所有对象(我可以在这个Game对象中执行此操作吗?或者我是否需要将其包装?)

var Game = function() {
    this.data      = [];
}

Game.prototype = {

    add: function(game) {
        this.data.push(game);   
    },
    update: function(game) {
        for(i = 0; i < this.data.length; i++) {
            if(this.data[i].id == game.id) {
                this.data[i].name = game.name;
             }
         }
    },
    get: function() {
        console.log(this.data);
    }
}


var g1 = new Game;
g1.add({id: '5', name: 'firstname'});
g1.add({id: '6', name: 'secondname'});

var g2 = new Game;
g2.add({id: '5', name: 'firstname'});
g2.add({id: '6', name: 'secondname'});

g1.update({id: '5', name: 'firstname-updated'})

g1.get();
g2.get();

基本上,如果你运行它,你会看到g1.get()用更新后的id 5写入数据,其中g2仍然有原始id 5,名字叫'firstname'。

非常感谢您的帮助!

编辑:只想添加,我仍然希望有多个对象。并不总是,每个对象都有匹配的ID。但如果他们这样做,他们都应该更新。

2 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

function Game() {
  this.data = [];
}

// Object to store games with the same id
Game.games = {};

Game.prototype.add = function(game) {

  // Add the game to the existing array with same id
  if (Game.games[game.id]) {
    Game.games[game.id].push(game);

  // Or create new array if first with this id
  } else {
    Game.games[game.id] = [game];
  }
  // other stuff
}

// Update all games with same id
Game.prototype.update = function(game) {
  var games = Game.games[game.id]
  // games is a reference to an array of all the games with the same id
}

答案 1 :(得分:0)

将您的代码更新为以下内容以获得所需的结果:

        var Game = function() {
            //this.data      = [];
        }

        Game.prototype = {

            data : [],

            add: function(game) {
                var found = false;
                for(i = 0; i < this.data.length; i++) {
                    if(this.data[i].id == game.id) {
                        found = true;
                        break;
                     }
                 }
                if( !found ) {
                    this.data.push(game);   
                }
            },
            update: function(game) {
                for(i = 0; i < this.data.length; i++) {
                    if(this.data[i].id == game.id) {
                        this.data[i].name = game.name;
                     }
                 }
            },
            get: function() {
                console.log(this.data);
            }
        };