0

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?

4

1 回答 1

2

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.

于 2013-09-15T13:44:05.383 回答