I’ve learned that using the deep copy in inheritance fixes the problem when you’re inheriting a child object when later modifying a child’s property, you’re changing the parent’s property as well because it points to the same object.
I read this awesome book but I’m very confused about what this code means:
function deepCopy(p, c) {
//Couldn't you just put c = { } instead?
var c = c || { };
for(var i in p) {
//What's the meaning of using the constructor property to check the object?
if(typeof p[x].constructor ==== 'object') {
//What's the meaning of the ternary operator having the { } object?
c[x] = (p[x] === Array) ? [] : { };
//I don't get what's the meaning of invoking deepCopy().
deepCopy(p[x], c[x])
}
else {
c[x] = p[x];
}
}
return c;
}
Sorry if I confuse anyone in my code comments. It would be appreciated if anyone can just walk me through the use of the meaning of the code inside the for-in loop.
I understand how the ternary operator works. I was just a bit confused regarding literal whether it was creating a new array or modifying it within the child object. I understand this part now.
Values such as strings or numbers or booleans, those can be copied straight across without any trouble.
The only two situations where a deeper copy is needed is in regards to nested information, such as arrays or objects. That’s why that’s being done.