Vlad Vlad - 24 days ago 9
Javascript Question

JS prototype and inheritance

In my spare time I try to learn a little bit of JS, but I stuck with the topic in subject.



var person = new Person("Bob", "Smith", 52);
var teacher = new Teacher("Adam", "Greff", 209);

function Humans(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}

function Person(firstName, lastName, age) {
Humans.call(this, firstName, lastName);
this.age = age;
}

Person.prototype = Object.create(Humans.prototype);

Person.prototype.fullDetail = function() {
return this.firstName + " " + this.lastName + " " + this.age;
};


function Teacher(firstName, lastName, roomNumber) {
Humans.call(this, firstName, lastName);
this.room = roomNumber;
}

Teacher.prototype = Object.create(Humans.prototype);

Teacher.prototype.fullDetail = function() {
return this.firstName + " " + this.lastName + " " + this.room;
};

person.fullDetail();





Can anybody tell me why I cant execute
person.fullDetail();
?

If you could make some comments with your version of code, I would be very grateful, thanks.

Answer

Because you're creating your objects before you've defined what their prototypes should be.

When you do

var person = new Person ("Bob", "Smith", 52);

you're making an object based on the current definition of Person. Later in that code, you're changing the prototype of Person in it's entirety

Person.prototype = Object.create(Humans.prototype);

To fix this, create your objects after you're done re-assigning the prototype.

function Humans(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

function Person(firstName, lastName, age) {
  Humans.call(this, firstName, lastName);
  this.age = age;
}

Person.prototype = Object.create(Humans.prototype);

Person.prototype.fullDetail = function() {
  return this.firstName + " " + this.lastName + " " + this.age;
};


function Teacher(firstName, lastName, roomNumber) {
  Humans.call(this, firstName, lastName);
  this.room = roomNumber;
}

Teacher.prototype = Object.create(Humans.prototype);

Teacher.prototype.fullDetail = function() {
  return this.firstName + " " + this.lastName + " " + this.room;
};

var person = new Person("Bob", "Smith", 52);
var teacher = new Teacher("Adam", "Greff", 209);
console.log(person.fullDetail());