When I try to call the method( getdetails() method of Teacher ) of child constructor function the parent constructor method is being called . Isn't the child method supposed to shadow the parent method . How to call the child constructor method getDetails()?
let Person = function() { };
Person.prototype.personName = "Smith";
Person.prototype.age = 37;
Person.prototype.getDetails = function() {
return `Person Name: ${this.personName}. Age is ${this.age}`;
};
let Teacher = function() { };
Teacher.prototype.mainSubject = "Physics";
Teacher.prototype.getDetails = function() {
return `Main subject is ${this.mainSubject}`;
};
Teacher.prototype = Object.create(Person.prototype); // inheritance
let teacher1 = new Teacher();
console.log(teacher1.getDetails());
You assign a new object to Teacher.prototype therefore losing everything you assigned to it beforehand. You should create the object before everything else.
let Person = function() { };
Person.prototype.personName = "Smith";
Person.prototype.age = 37;
Person.prototype.getDetails = function() {
return `Person Name: ${this.personName}. Age is ${this.age}`;
};
let Teacher = function() { };
Teacher.prototype = Object.create(Person.prototype); // inheritance
Teacher.prototype.mainSubject = "Physics";
Teacher.prototype.getDetails = function() {
return `Main subject is ${this.mainSubject}`;
};
let teacher1 = new Teacher();
console.log(teacher1.getDetails());
But nowadays you could also use classes instead of functions.
class Person {
personName = "Smith";
age = 37;
getDetails() {
return `Person Name: ${this.personName}. Age is ${this.age}`;
}
}
class Teacher extends Person {
mainSubject = "Physics";
getDetails() {
return `Main subject is ${this.mainSubject}`;
}
}
let teacher1 = new Teacher();
console.log(teacher1.getDetails());