Crockford’s Prototypal inheritance – Issues with nested objects

There is no inconsistency. Just don’t think of nested objects: a direct property of an object is always either on its prototype or an own property. It’s irrelevant wheter the property value a primitive or an object.

So, when you do

var parent = {
    x: {a:0}
};
var child = Object.create(parent);

child.x will be referencing the same object as parent.x – that one {a:0} object. And when you change a property of it:

var prop_val = child.x; // == parent.x
prop_val.a = 1;

both will be affected. To change a “nested” property independently, you first will have to create an independent object:

child.x = {a:0};
child.x.a = 1;
parent.x.a; // still 0

What you can do is

child.x = Object.create(parent.x);
child.x.a = 1;
delete child.x.a; // (child.x).a == 0, because child.x inherits from parent.x
delete child.x; // (child).x.a == 0, because child inherits from parent

which means they are not absolutely independent – but still two different objects.

Leave a Comment