The fact that objects (including functions and arrays) are copied by reference could sometimes lead to results you don't expect.
Let's create two constructor functions and add properties to the prototype of the first one:
> function Papa() {} >function Wee() {} >Papa.prototype.name = 'Bear'; >Papa.prototype.owns = ["porridge", "chair", "bed"];
Now, let's have Wee
inherit from Papa
(either extend()
or extend2()
will do):
>extend2(Wee, Papa);
Using extend2()
, the Wee
function's prototype inherited the properties of Papa.prototype
as its own.
>Wee.prototype.hasOwnProperty('name'), true >Wee.prototype.hasOwnProperty('owns'), true
The name
property is primitive so a new copy of it is created. The property owns
is an array object so it's copied by reference:
>Wee.prototype.owns; ["porridge", "chair", "bed"] >Wee.prototype.owns=== Papa.prototype.owns; true
Changing the Wee
function's copy of name
doesn't affect Papa
:
>Wee.prototype.name += ', Little Bear'; "Bear, Little Bear" >Papa.prototype.name; "Bear"
Changing the Wee
function's owns
property, however, affects Papa
, because both properties point to the same array in memory.
>Wee.prototype.owns.pop(); "bed" >Papa.prototype.owns; ["porridge", "chair"]
It's a different story when you completely overwrite the Wee
function's copy of owns
with another object (as opposed to modifying the existing one). In this case Papa.owns
keeps pointing to the old object, while Wee.owns
points to a new one.
>Wee.prototype.owns= ["empty bowl", "broken chair"];
>Papa.prototype.owns.push('bed'),
>Papa.prototype.owns;
["porridge", "chair", "bed"]
Think of an object as something that is created and stored in a physical location in memory. Variables and properties merely point to this location, so when you assign a brand new object to Wee.prototype.owns
you essentially say, "Hey, forget about this other old object, move your pointer to this new one instead".
The following diagram illustrates what happens if you imagine the memory being a heap of objects (like a wall of bricks) and you point to (refer to) some of these objects.
A.color === "white"
would be true.If you want to address the problem that objects are copied by reference, consider a deep copy, described further.
18.216.251.37