1

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 ?????????????????????
Aleksey
  • 88
  • 6
  • Because `a.first` is a reference to an array. When assigning `b.first = a.first` (which is what *extend* seems to do) then `b` gets a reference to the same array. – RobG Apr 05 '13 at 05:57
  • You need a **deep** copy of your object. http://stackoverflow.com/questions/122102/most-efficient-way-to-clone-a-javascript-object/122704#122704 – yunzen Apr 05 '13 at 06:02
  • In the real I use some of deepExtend, but it seems my version is not good. I will try other versions. Thanks! – Aleksey Apr 05 '13 at 06:35

1 Answers1

5

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.

https://stackoverflow.com/a/728694/1570248

Community
  • 1
  • 1
Abe Haskins
  • 1,378
  • 1
  • 7
  • 9