0

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 ?????????????????????
3
  • 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. Commented Apr 5, 2013 at 5:57
  • You need a deep copy of your object. stackoverflow.com/questions/122102/… Commented Apr 5, 2013 at 6:02
  • In the real I use some of deepExtend, but it seems my version is not good. I will try other versions. Thanks! Commented Apr 5, 2013 at 6:35

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.