Deep copy
The function extendCopy()
, discussed previously, creates what is called a shallow copy of an object, just like extend2()
before that. The opposite of a shallow copy would be, naturally, a deep copy. As discussed previously (in the Heads-up when copying by reference section ), when you copy objects you only copy pointers to the location in memory where the object is stored. This is what happens in a shallow copy. If you modify an object in the copy, you also modify the original. The deep copy avoids this problem.
The deep copy is implemented in the same way as the shallow copy: you loop through the properties and copy them one by one. But, when you encounter a property that points to an object, you call the deep copy function again:
function deepCopy(p, c) { c = c || {}; for (vari in p) { if (p.hasOwnProperty(i)) { if (typeof p[i] === 'object') { c[i] = Array.isArray(p[i]) ? [] : {}; deepCopy(p[i], c[i]); } else { c[i] = p[i]; } } }...