0

(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);
Patricio Vargas
  • 5,236
  • 11
  • 49
  • 100

1 Answers1

1

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 .prototypes 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
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320