Java Reference
In-Depth Information
Note: Shallow and Deep Copies
When objects are copied by assignment, they are only copied by reference.
This means that another object is not actually created in memory; the new
reference will just point to the old object. Any changes that are made to
either objects will affect both of them. Arrays and functions are objects, so
whenever they're copied by assignment they will just point to the same ob-
ject, and when one changes they'll all change. This is known as making a
shallow copy
of an object. A
deep
or
hard copy
will create a completely
new object that has all the same properties as the old object. The difference
is that when a hard copy is changed the original remains the same, but when
a shallow copy is changed so will the original.
This affects our mixin function when we try to copy a property that is an
array or object, as can be seen in this example:
a = {};
b = { myArray: [1,2,3] };
a.mixin(b);
<< { myArray: [1,2,3] }
a
now has a reference to the
myArray
property in the
b
object, rather than
its own copy. Any changes made to either object will affect them both:
b.myArray.push(4);
<< 4
b.myArray;
<< [1,2,3,4]
a.myArray; // This has also changed
<< [1,2,3,4]
There is a simple way to sidestep that only a shallow copy is made. The
mixin
method is
used to copy objects, so if a property is an array or nested object, we just call the
mixin
method recursively on it to copy its properties one at a time instead of using assignment.
