JavaScript uses prototypal inheritance where objects inherit directly from other objects through a prototype chain. Each object has an internal [[Prototype]] link that forms a chain used for property lookup until null is reached.
Prototype Chain Basics:
Key Concepts:
Modern Inheritance Patterns:
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(`${this.name} makes a sound`);
};
function Dog(name, breed) {
Animal.call(this, name);
this.breed = breed;
}
// Set up inheritance
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() {
console.log(`${this.name} barks!`);
};
const rex = new Dog('Rex', 'German Shepherd');
// Prototype chain:
// rex -> Dog.prototype -> Animal.prototype -> Object.prototype -> null
rex.bark(); // 'Rex barks!' (own prototype)
rex.speak(); // 'Rex makes a sound' (inherited)
rex.toString(); // '[object Object]' (from Object.prototype)