Mateusz Mazurek
Mateusz Mazurek

Reputation: 101

All properties are set to last loop iteration value [why?]

Sample code:

var functions = {
 testFunction: function(){
  console.log('test');
 }      
};
var functionsClones = [];
for(i in [1,2,3]){
 var functionsClone = $.extend({}, functions);
 functionsClone.testFunction.i = i;
 functionsClones.push(functionsClone);
}

$.extend is jQuery function which allows to clone object instead of reffering to it.

Now let's print set properties:

$.each(functionsClones, function(key, functionsClone){
 console.log(functionsClone.testFunction.i);
});

It outputs 3 times '2' instead of 0, 1, 2. What's wrong with this code?

Upvotes: 0

Views: 104

Answers (1)

user2736012
user2736012

Reputation: 3543

Because you're setting i on the same testFunction object (which happens to be a function). You're not creating a new function in each iteration of the loop.

Therefore, at the end of the loop, the function testFunction object holds the last value it received.

Because JavaScript only gives you reference to objects, and not the objects themselves, a copy isn't made.

To make a separate copy, you'd need to create the function in the loop.

Upvotes: 2

Related Questions