Learn the concept
Prototypes & Inheritance
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:
new calling, non-enumerable methods, and proper builtin extendingfunction 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)Building UI framework component systems where base components provide shared lifecycle methods and specialized components extend them through prototype inheritance
Creating extensible plugin systems where a base plugin class defines the required interface and third-party plugins extend it via the prototype chain
Implementing database model hierarchies where a base Model class provides CRUD operations and specific models inherit and customize behavior
Build a custom EventEmitter using both prototype functions and ES6 class syntax, implementing on, off, emit, and once methods
Implement a mixin utility that composes multiple behaviors onto a class via prototype manipulation with conflict resolution