How to access a method from the parent prototype in the child as we can with classes?
In a class when we have a method in the parent class we can access the same in the child class. In the prototype way of doing the same, I'm not able to access the parent prototype method
With class:
class Person {
constructor(name, id){
this.name = name;
this.id = id;
}
printDetails (){
console.log(`Printing details in parent class :${this.name} : ${this.id}`);
}
}
class Employee extends Person {
constructor(name, id, salary){
super(name, id);
this.salary = salary;
}
employeeInfo(){ // this will exist in the prototype of Employee class, not in the instance.
return `${this.name} : ${this.id} : ${this.salary}`
}
}
const a = new Employee('Mary', 1, 123456);
// console.log(a.employeeInfo())
// a.printDetails();
With Function and prototype:
let PersonF = function(name, id){
this.name = name;
this.id = id;
}
PersonF.prototype.getDetails = function(){ // Dont use arrow here, the this for the arrow is window, not the this of the object
console.log(`Printing details in parent in function way :${this.name} : ${this.id}`);
}
let pers = new PersonF('Person', 111);
// pers.getDetails();
let EmployeeF = function(name, id, salary){
PersonF.call(this, name, id); // this is same as super in class. here first param will take the this of the context and then other params
this.salary = salary;
}
Object.setPrototypeOf(EmployeeF, PersonF.prototype); // This is same as extends in class.
EmployeeF.prototype.printDetails = function(){
console.log(`${this.name} : ${this.id} : ${this.salary}`);
}
const emp = new EmployeeF('John', 1 , 10000000);
// emp.printDetails();
emp.getDetails(); // Getting an error here.