Why b.first[0] return "t" and how I can avoid this?
I need safe "q" in b.first[0]
var extend = function(o,p){
for(prop in p){
o[prop] = p[prop];
}
return o;
};
var a = {first:['q','w']};
var b = {};
extend(b,a);
document.write(a.first[0]); //q
document.write(b.first[0]); //q
a.first[0] = 't';
document.write(a.first[0]); // t
document.write(b.first[0]); // t ?????????????????????
1 Answer 1
This is an issue relating to the concept that extending b by a doesn't recreate the data from a. If some of the data is an object (like an Array), it instead just "points" to that array instead of creating a new, identical array. Essentially you're storing two pointers to the same array, so when you change one, you change the other.
Here is a answer which discusses the idea of "cloning" an object in Javascript in more detail.
answered Apr 5, 2013 at 5:53
Abe Haskins
1,3781 gold badge7 silver badges9 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js
a.firstis a reference to an array. When assigningb.first = a.first(which is what extend seems to do) thenbgets a reference to the same array.