I am still leaning Javascript and I encountered twice a behavior I didn't expect. I would like to understand why it happens and what I should learn to understand it better.
First case: I tried to call a function using a file input filelist
as argument. Right after I call my function, I set to null
the file input value. In my function, I use a callback that can't get back my fileList since the file input is reseted.
What I don't understand:
I expected the file list object to be somehow "copied" once it was sent to the function. Why changing the original object affects the callback?
Second case: I use a JSON object called values
to store, well, values. I iterate on a collection and update a name
field of my values
object using the iteration index before inserting the values
object inside another JSON object. See the code:
var myBaseName = "file"
_.each (myCollection, function(file, i){
values.name = myBaseName + " - " + i
console.log(values.name); //here the name appears correctly,
//i.e. "file - 0", "file - 1"...
values.size = file.size,
values.type = file.type,
allFiles[i]=values;
});
console.log (allFiles);//here the name appears as the last set,
//i.e. if my collection has 2 objects;
//they both appear as "file - 1"
What I don't understand:
Why is it updating and not simply copied? This is, I expect, the same kind of mechanism than in my first case. I used to code in .net and I never encountered such a behavior. I expected a json object to be some kind of enhanced string.