How does inheritance work in JavaScript

Inheritance in JavaScript works primarily through prototype chaining. When an object is created, it has a hidden internal link to another object, known as its prototype. This prototype itself can have its own prototype, and so on, forming a chain. When a property or method is accessed on an object, JavaScript will look up the chain until it finds the property, or returns undefined if it doesn't exist.

Here’s a basic example demonstrating inheritance in JavaScript:

// Base class function Animal(name) { this.name = name; } Animal.prototype.speak = function() { console.log(this.name + ' makes a noise.'); }; // Derived class function Dog(name) { Animal.call(this, name); // Call the parent constructor } // Inherit from Animal Dog.prototype = Object.create(Animal.prototype); Dog.prototype.constructor = Dog; // Overriding speak method Dog.prototype.speak = function() { console.log(this.name + ' barks.'); }; // Example usage const dog = new Dog('Rex'); dog.speak(); // Output: Rex barks.

Javascript Inheritance Prototype Object-Oriented Programming