(Please close IF duplicate)
Given the following scenario:
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;
}
//Teacher.prototype = Person.prototype;
//Teacher.prototype = Object.create(Person.prototype);
Teacher.prototype.constructor = Teacher;
const t = new Teacher('John','Smith','Math');
What would be the difference of using this?
Teacher.prototype = Person.prototype;
or this
Teacher.prototype = Object.create(Person.prototype);
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.