0

in this page https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Inheritance#setting_teachers_prototype_and_constructor_reference...

to inherit prototypes, why does it use Teacher.prototype = Object.create(Person.prototype); and not simply using

Teacher.prototype = Person.prototype;
shiyon sufa
  • 179
  • 3
  • 7
  • For what it's worth this looks like ES5 material. In ES6 this is `class Teacher extends Person` with [classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes). – tadman Apr 07 '21 at 20:09
  • oh, so this kind of programming is outdated ? @tadman – shiyon sufa Apr 07 '21 at 20:10
  • Yeah, it's pretty much defunct now that ES6 is supported by virtually anything you'll see in the wild. The new class-based approach fixes a *lot* of the things that made JavaScript classes unnecessarily ugly. – tadman Apr 07 '21 at 20:12
  • @tadman It's still important to understand how prototypes and the inheritance chain of a class work, and how the `Object.create` primitive is a basic building block. – Bergi Apr 07 '21 at 20:36
  • @Bergi Debatable. It really depends on what your objectives are. – tadman Apr 07 '21 at 20:41
  • Without `Object.create`, if the property of the `prototype` was an Object, that Object would be referenced by both instances, so setting that Object property in one `new` instance would appear to affect other `new` instances. – StackSlave Apr 07 '21 at 21:02

1 Answers1

1

The specifics here are to do with how the ES5 and prior versions of inheritance work. The prototype property defines functions that class members can use.

If you were to directly assign then any functions added to Teacher would also back-propagate to Person, as in:

Teacher.prototype = Person.prototype;
Teacher.prototype.name = function(...) { }

Where that name() function now impacts Person as well. Object.create() effects a cloning operation meaning the two prototypes are now independent.

The way this plays out in ES6 is a lot different, and arguably a lot cleaner:

class Teacher extends Person {
  name() {
    // ...
  }
}

This still generates the same Teacher.prototype at the end of the day, the internals are effectively the same, but the composition of classes is vastly simplified.

tadman
  • 208,517
  • 23
  • 234
  • 262