Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 464
vlad Avatar asked Jan 17 '26 15:01

vlad


1 Answers

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());
like image 50
Mike Cluck Avatar answered Jan 20 '26 03:01

Mike Cluck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!