I have given many interviews on javascript. One question that is always common is "How Inheritance is achieved, explain with an example".
What I explain to the interviewer is more or less same as given in MDN site
My piece of code:
//Parent Class
var Employee = function(name,salary) {
this.name = name;
this.salary = salary;
}
Employee.prototype.WelcomeMessage = function() {
return ("Welcome "+this.name)
}
Employee.prototype.getSalary = function() {
return this.salary
}
//Child Class
var Infra = function(name,salary) {
Employee.call(this,name,salary);
//Child should have its own get Salary method
Infra.getSalary = function() {
return "this is salary for child"
}
}
Infra.prototype = Object.create(Employee.prototype);
Infra.prototype.constructor = Infra ;
// Created instance of child to achieve Inheritance
var childInstance = new Infra("Jack","$1000")
childInstance.name //Return Jack
childInstance.WelcomeMessage() //Return Welcome Jack
childInstance.getSalary //return "this is salary for child" - this method was
// overridden by child
But every time i gave this example interviewer is not ok with this solution . They say in this inheritance example "Infra.prototype.constructor = Infra ;" is used , which is not recommended . You should use Object.assign with self invoking functions to achieve inheritance .
I generally defend it by saying this also achieve desired result and the same is given in MDN.
What is the correct way to achieve inheritance?