0
const person = {
  isHuman: false,
  printIntroduction: function() {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  }
};

const me = Object.create(person);

me.name = 'Matthew'; // "name" is a property set on "me", but not on "person"
me.isHuman = true; // inherited properties can be overwritten

me.printIntroduction();

Instead of writing :

const me = Object.create(person);

why don't write

const me = person;

instead? I see this all the time but still don't get the point.

Barmar
  • 669,327
  • 51
  • 454
  • 560
  • 2
    `Object.create(person)` creates a new object whose *prototype* is `person`. It's a significantly different operation. – Pointy Jul 14 '21 at 18:11
  • 2
    `const me = person;` makes both variables refer to the same object. – Barmar Jul 14 '21 at 18:16
  • 2
    Just run `me = person; me.name = 'Matthew'; console.log(person);` and you will find out why. – axiac Jul 14 '21 at 18:18
  • 2
    Ask yourself, what will you do when you want to create `me`, `you`, `they`, all having access to that method, but with (obviously) different output? – trincot Jul 14 '21 at 18:19
  • There is nothing wrong with that... so long as you only want to ever create a single person. The minute you need more of them, `Object.create` or the gloss that is the `class` syntax will allow them to share functions such as `printIntroduction` without stepping on one another. – Scott Sauyet Jul 14 '21 at 18:21
  • Using the second approach would end up with only 1 object ever, whereas the first approach will create as many objects as times it is used. For more on Object.create with regards to objects, please see the list of duplicates. – Travis J Jul 14 '21 at 18:24
  • This has been marked as duplicate but the questions linked while helpful to the asker, are different questions all together and discuss a much more complex matter. OP read the comments rather than the links – Jazz Jul 14 '21 at 18:31
  • @Jazz I've reopened the question, then found some more suitable duplicates – Bergi Jul 14 '21 at 18:56
  • @TravisJ The duplicates you found only talked about using `Object.create` for creating a prototype object of a class – Bergi Jul 14 '21 at 18:57
  • @Bergi - The new set of duplicates are more than likely not going to be of use for the OP. They are no better than the first two comments left here. While they depict a similar test case for identifying a misunderstanding of the Object.create feature, they are not going to be helpful to remedying the underlying confusion. – Travis J Jul 14 '21 at 20:03
  • Wow I didn't notice that. I thought it create a new one as well with assignment. Does this only happen to objects, bcs the assignment looks closer to a true equal operator now rather than being asign operator. – Ihsan Nurul Iman Jul 15 '21 at 16:03

0 Answers0