JavaScript Object.create — inheriting nested properties

前端 未结 3 1547
长情又很酷
长情又很酷 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: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'
    };
    

提交回复
热议问题