title: Backbone.js collection.at(i).get('person') references to the same model in a loop
body: <p>I have</p>
  
  <pre><code>data = {
    "name1": "id1"
    , "name2": "id2"
    , "name3": "id3"
    , "name4": "id4"
    , "name5": "id5"
  }
  
  var MyCollection = Backbone.Collection.extend({
    model: Backbone.Model
  })
  
  var myCollection = new MyCollection();
  
  myCollection.fetch({
    success: function(collection, response) {
      var i = 0;
  
      for (var name in data) {
        if ( !data.hasOwnProperty( name ) ) continue;
  
        (function(theName) {
          var obj = collection.at(i).get('object');
          obj.id = data[theName];
          obj.displayName = theName;
          collection.at(i).set({"object": obj});
        })(name);
        i++
      }
    }
  })
  </code></pre>
  
  <p>The <code>response</code> contains</p>
  
  <pre><code>[
    null
    , {
      "_id" : "some id"
      , "object": {
        "displayName": "name1"
        , "id": "id1"
      }
    }
    , null
    , {
      "_id" : "some id"
      , "object": {
        "displayName": "name1"
        , "id": "id1"
      }
    }
    , null
  ]
  </code></pre>
  
  <p>Some of the <code>null</code> value is because they does not exist in database. The collection on fetch will create a default model for those <code>null</code>, which the same structure, but no <code>_id</code>, and properties of <code>object</code>  are empty strings.</p>
  
  <p>The problem I have is after the loop, all the models has the same attributes as the last one in <code>data</code>, i.e., <code>name5</code> and <code>id5</code>. I checked <code>obj</code> in each iteration, and it was indeed the same object. Thus, for each iteration, all models in the collection is set the same attributes.</p>
  
  <p>Variable <code>name</code> in each iteration changes according to <code>data</code>, as well as <code>i</code> is increased. I also put the iteration inside a closure to make sure the scope is right.</p>
  
  <p>Why Backbone behaves that way?</p>
  
  <hr>
  
  <h3>Update</h3>
  
  <p>It turned out that because of those <code>null</code> values in the <code>response</code> that made Backbone model behave so weird. I overridden <code>parse</code> function in the collection to set default values for the <code>null</code> object instead of relying on defaults value of the model, and it works.</p>