If you use the plain assignment method, changes to Teacher.prototype
will also affect Person.prototype
. This is not a good idea, because while a Teacher is a Person, a Person is not necessarily a Teacher:
function Person(first, last) {
this.name = {
first,
last
};
};
Person.prototype.greeting = function() {
console.log('Hi! I\'m ' + this.name.first + '.');
};
function Teacher(first, last, subject) {
Person.call(this, first, last);
this.subject = subject;
}
// Bad:
Teacher.prototype = Person.prototype;
// Because:
Teacher.prototype.teachesClass = () => true;
// Person.prototype now has that too:
const p = new Person();
console.log(p.teachesClass());
Now, both .prototype
s are the same, so any mutations to one will affect the other. This is pretty much never what you want.
In contrast, when you use the Object.create
method, assignments to Teacher.prototype
will only affect Teacher.prototype
. The object that Teacher.prototype
inherits from, Person.prototype
, will not be changed:
function Person(first, last) {
this.name = {
first,
last
};
};
Person.prototype.greeting = function() {
console.log('Hi! I\'m ' + this.name.first + '.');
};
function Teacher(first, last, subject) {
Person.call(this, first, last);
this.subject = subject;
}
// Good:
Teacher.prototype = Object.create(Person.prototype);
// Because:
Teacher.prototype.teachesClass = () => true;
// Person.prototype does not have teachesClass
const p = new Person();
console.log(p.teachesClass);
Looking at the prototype chain:
Teacher.prototype = Person.prototype;
// You get:
Teacher.prototype <- Object.prototype
Person.prototype <- Object.prototype
Teacher.prototype === Person.prototype // (same object)
// Compare to
Teacher.prototype = Object.create(Person.prototype);
// You get:
Teacher.prototype <- Person.prototype <- Object.prototype