Inheritance in JavaScript
JavaScript is dynamic and before ES6 JavaScript did not provide a class implementation. The inheritance was mainly prototype-based inheritance.
prototype-based inheritance
In prototype-based inheritance, the inheritance is done in multiple steps. The following code block shows how the ScienceStudent inherits properties from the Student using the prototypal inheritance:
function Student(academicNumber) { this.academicNumber = academicNumber; } Student.prototype.Learn = function() { console.log('All students need to learn English'); }; function ScienceStudent(academicNumber) { Student.call(this, academicNumber); } ScienceStudent.prototype = Object.create(Student.prototype); // or ScienceStudent.prototype = Student.prototype; ScienceStudent.prototype.LearnScience = function() { console.log('All science students need to learn Physics'); }; const scienceStudentObj = new ScienceStudent(310202); scienceStudentObj.Learn(); // All students need to learn English scienceStudentObj.LearnScience(); // All science students need to learn Physics
In modern JavaScript, the ES6 simplified these steps by using the extends and super keywords. Following is the example of the above use case using class and super keywords:
class Student { constructor(academicNumber) { this.academicNumber = academicNumber; } learn() { console.log('All students need to learn English'); } } class ScienceStudent extends Student { constructor(academicNumber) { super(academicNumber); } LearnScience() { console.log('All science students need to learn Physics'); } } const scienceStudentObj = new ScienceStudent(35353); scienceStudentObj.learn(); scienceStudentObj.LearnScience();