JavaScript Object.create — inheriting nested properties

前端 未结 3 1551
长情又很酷
长情又很酷 2020-12-14 04:07

I\'ve come across a peculiarity with Douglas Crockfords Object.create method which I\'m hoping someone might be able to explain:

If I create an object - say \'person

相关标签:
3条回答
  • 2020-12-14 04:30

    The reason the name attribute isn't copied is because object literals in JavaScript are always references, therefore the reference is copied (not its content) ... so it is not because it is deeper in the prototype chain or because it's doing a shallow copy.

    0 讨论(0)
  • 2020-12-14 04:36

    That happens because anotherPerson.name is an object and it is stored upper in the prototype chain, on the original person object:

    //...
    var anotherPerson = Object.create(person);
    anotherPerson.hasOwnProperty('name'); // false, the name is inherited
    person.name === anotherPerson.name; // true, the same object reference
    

    You can avoid this by assigning a new object to the name property of the newly created object:

    // create anotherPerson from person
    var anotherPerson = Object.create(person);
    
    anotherPerson.name = {
      first: 'Stephen',
      last: 'Merchant'
    };
    
    0 讨论(0)
  • 2020-12-14 04:39

    The problem is that Object.create only does a shallow copy, not a deep copy, so person.name and anotherPerson.name both point to the same Object instance.

    Edited

    While it's true that person.name === anotherPerson.name, my explanation for why this is true is incorrect. See @CMS's answer for the correct explanation.

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