to inherit prototypes, why does it use
Teacher.prototype = Object.create(Person.prototype);
and not simply using
Teacher.prototype = Person.prototype;
to inherit prototypes, why does it use
Teacher.prototype = Object.create(Person.prototype);
and not simply using
Teacher.prototype = Person.prototype;
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.