Why does the code below print "Tree", "Tree", and not "Bear", "Tree"?
var file_array = new Array(100);
var fileobject = {name: null , folder: null , url: null , modified: null};
fileobject.name = "Bear";
file_array[0] = fileobject;
fileobject.name = "Tree";
file_array[1] = fileobject;
console.log(file_array[0].name);
console.log(file_array[1].name);
1 Answer 1
There's only one object involved. Assigning an object value with = assigns a reference to the object, not a copy.
It's possible to copy objects, but in the general case it can grow to a very hard problem (due to things like reference cycles). If you need lots of those objects, a better solution would be to write a function that returns a fresh object when you call it:
function makeFileObject(name) {
return {name: name , folder: null , url: null , modified: null};
}
file_array[0] = makeFileObject("Bear");
file_array[1] = makeFileObject("Tree");
answered Feb 16, 2017 at 16:09
Pointy
415k62 gold badges600 silver badges633 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Steve
Thanks a lot, been pulling my hair out over this one!
lang-js