Crockford's Prototypal inheritance - Issues with nested objects

后端 未结 3 917
借酒劲吻你
借酒劲吻你 2020-11-22 01:21

I\'ve been reading \"Javascript: The Good Parts\" by Douglas Crockford - and while it\'s a bit extreme, I\'m on board with a lot of what he has to say.

In chapter

3条回答
  •  执念已碎
    2020-11-22 02:22

    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.

提交回复
热议问题