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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With