Updating inherited property

后端 未结 2 1273
感情败类
感情败类 2021-01-20 12:31
var foo = {x: 1}
var bar = {__proto__: foo} // __proto__ specific to implementation
var bar = Object.create(foo) // same result as above with standard API 
console.l         


        
相关标签:
2条回答
  • 2021-01-20 12:42

    It's all about prototypes. bar object has no x property, so when you try to access it, prototypes chain will be involved, and you will get value of foo.x. Then you update foo.x, and while accessing bar.x you will see another value also.

    But when you set bar.x, x property will be created in bar object. foo.x is another one so it will stay the same.

    And you should avoid using __proto__ in your code. It's browser specific feature (that's why it has underscores in name).

    0 讨论(0)
  • 2021-01-20 12:56

    Assigning to an object property creates or updates the object's own property, there is no search on the prototype chain for an inherited property.

    See ECMAScript Simple Assignment ( = ) §11.13.1.

    0 讨论(0)
提交回复
热议问题