How does inheritance happens in Javascript
Inheritance Explanation
Prototype-Based Inheritance
JavaScript uses prototypes rather than classical inheritance. Every
object has an internal link to another object called its prototype. When
you try to access a property on an object, JavaScript first looks at the
object itself, then checks its prototype, then the prototype’s
prototype, and so on up the chain.
Code examples
function House(amenities) {
this.amenities = amenities;
}
// Injecting new function called getAmenities with the help of prototype
House.prototype.getAmenities = function() {
return this.amenities;
}
function RentingHouse(amenities, location) {
// Call base/parent function inside this child with the help of 'call function'
House.call(this, amenities);
this.getLocation = function() {
return location;
}
}
//Linking Prototypes (Key Step)
RentingHouse.prototype = Object.create(House.prototype);
RentingHouse.prototype.constructor = RentingHouse;
// Create instance of child
const rentingHouse = new RentingHouse({ giserAvailable: true, attachBathroom: true, freezAvailable: true }, 'Bengalore');
console.log(rentingHouse.getAmenities());
Output
{
giserAvailable: true,
attachBathroom: true,
freezAvailable: true
}
Modern Way – ES6 class Inheritance (Recommended)
// Making class as abstract due to inheritance only and no more intance to be created
abstract class House {
constructor(protected amenities: any) { }
getAmenities() {
return this.amenities;
}
}
class RentingHouse extends House {
constructor(protected amenities: any, protected location: string) {
/**
* Inherited and parent constructor value is passing
* Remember: super special function only needs here if child class has constructor and parent wants value via parametrized constructor
*/
super(amenities);
}
getLocation() {
return this.location;
}
}
const rentHouse = new RentingHouse({ giserAvailable: true, attachBathroom: true, freezAvailable: true }, 'Bengalore');
console.log(rentHouse.getAmenities());
console.log(rentHouse.getLocation());
Output
{
"giserAvailable": true,
"attachBathroom": true,
"freezAvailable": true
}
"Bengalore"
Key points to remember
- The extends keyword creates the inheritance relationship
- super() calls the parent class’s constructor
- Child classes can override parent methods or add new ones
- Under the hood, this still uses prototypes—it’s just easier to read and write
