Classical Inheritance
Introduced in ECMAScript6 (ES6) with the class keyword. Uses a class-based approach similar to other programming languages like Java or C++. Following are the methods through which class-based inheritance is achieved in JavaScript:
Inheritance using extend keyword
JavaScript ES6 classes support the extended keyword to perform class inheritance.
Example: Demonstrating class inheritance and method overloading in JavaScript.
Javascript
class automobile { constructor(name, cc) { this .name = name; this .cc = cc; } engine() { console.log(`${ this .name} has ${ this .cc} engine`); } } class car extends automobile { engine() { console.log( this .name, "has " , this .cc, "cc engine" ); } } let carz = new car( 'Rex' , "1149" ); carz.engine(); |
Rex has 1149 cc engine
Inheritance using the super keyword
Super keyword is used in classes to call the properties and methods of the parent class.
Example: Using super keyword for method invocation and inheritance in JavaScript.
Javascript
// Inheritance using super keyword in JS class Automobile { constructor(name) { this .name = name; } engine() { console.log( this .name, "has " , this .cc, "cc engine" ); } } class Car extends Automobile { constructor(name, cc) { super (name); // Additional properties for // the Car class this .cc = cc; } engine() { // the 'engine' method of the parent // class using 'super' super .engine(); console.log( this .name, "has " , this .cc, "cc engine" ); } } let carz = new Car( 'Rexton' , '1500' ); carz.engine(); |
Rexton has 1500 cc engine Rexton has 1500 cc engine
Inheritance in static members
Static members belong to their own class and not to their instances because inheritance also applies to the static members of the class.
Example: Demonstrating the inheritance in static members in JavaScript.
Javascript
// Inheritance in static members class Automobile { static staticMethod() { return 'Automobile static method' ; } } class car extends Automobile { static staticMethod() { return 'Car static method' ; } } console.log(Automobile.staticMethod()); console.log(car.staticMethod()); |
Automobile static method Car static method
JavaScript Inheritance
JavaScript inheritance is the method through which the objects inherit the properties and the methods from the other objects. It enables code reuse and structuring of relationships between objects, creating a hierarchy where a child object can access features of its parent object. Inheritance in JavaScript can be achieved in the following ways:
Table of Content
- Prototypal Inheritance
- Classical Inheritance
- Functional Inheritance