Solution
-
'tiger' 'large'
-
'lion' undefined
-
undefined 'large'
-
'lion' 'large'
Explanation
On the first line, an object cat
is created.
Its prototype is the object { type: 'lion' }
,
i.e. the argument of Object.create()
.
This means that cat.type
returns the string 'lion'
,
thanks to prototypal inheritance.
The JavaScript engine first looks for a property named type
on the cat
object.
If it doesn't find one, it looks in the prototype.
Here, the prototype happens to have a property named type
,
so the JavaScript engine stops climbing up the prototype chain.
But note that the type
property is not an own property
of cat
. It is "inherited" from its prototype.
In other words, at this point of the code, the object cat
doesn't have any own property, i.e. properties defined at its "level".
The second line of the code adds an own property named size
to the cat
object.
At this point, the cat
object looks like this:
{ size: 'large' }
.
Then, a copyCat
object is created by using the spread operator
(...
).
At this point, the copyCat
object looks like this:
{ size: 'large' }
.
Thanks to the use of the spread operator and to the fact that the
size
property has a primitive value (a string),
the copyCat
object happens to be a deep copy of the
cat
object.
In other words, the 2 objects are totally independent from one another:
an update of the value of the property size
on 1 object doesn't affect the other object and vice versa.
Then, a property named type
is added to the cat
object.
This doesn't change the copyCat
object.
Also, the cat
object now has an own property named
type
.
This own property overrides the type
property defined on the prototype of cat
.
A this point, cat.type
now returns the string
'tiger'
instead of the string
'lion'
.
To sum up, this is what the 2 objects look like:
-
cat
: { size: 'large', type: 'tiger' }
.
-
copyCat
: { size: 'large' }
.
copyCat
doesn't have a type
property, and none of its prototypes do.
Note that the prototypes of copyCat
are: Object.prototype
then null
.
So copyCat.type
returns the primitive value undefined
.
copyCat
has an own property size
.
copyCat.size
returns the string 'large'
.
Relevant resource(s):