0

Just had a quick question about why a certain order of assignment works and another doesn't.

I wanted to create a simple "inherit" / "copy" function (just for testing it) that copies properties from one object to another:

var cat = { tail:"yes", hairy:"yes, hairy" };
var dog = { sick:"extremely ill"};

function inherit(obj1, obj2) {
    for (var p in obj1) 
    {
    obj2[p] = obj1[p]; // this works, but "obj1[p] = obj2[p];" doesn't. Why??
    }
}

inherit(cat, dog);

console.log(dog.tail);

2 Answers 2

1

You are looping over all the properties of obj1, so all those properties exist on obj1.

If you try to copy from obj2 then you are trying to copy properties that don't exist (on that object), so you cause an error.

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

Comments

1

You're reading the properties var p in obj1, so those indexes only necessarily exist in obj1. As such, trying to assign obj1[p] = obj2[p]; won't work as expected, since there is no guarantee (and in your particular example this is certainly the case) that obj[p] is defined. This assignment will simply assign undefined to indexes in obj1 that don't exist in obj2 and copy the values whose indexes do exist in obj2.

You need to loop over each object's properties separately (i.e. two loops), although this also isn't a good idea, since any values with the same index on both object will result in one being wiped out. What are you actually trying to achieve by this? It seems a very dangerous/volatile thing to do.

2 Comments

+1 Of course, OP could control for where both objects have a particular key with at least obj2[p] = obj2[p] || obj1[p]; (or some variant if you might be assigning falsy values). If it's just a programming exercise to learn about loops and assignment, it's a fair question, IMO.
@Bryan, I didn't mean the question isn't a valid one, just that the intention/purpose of the code is unclear and not well defined. You could do many things with clashing keys, my problem was that the OP's intention in such a case was unclear.

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.