Inheritance in JavaScript
Key Concepts
Inheritance in JavaScript allows objects to inherit properties and methods from other objects. The key concepts include:
- Prototype Chain
- Constructor Functions
- Prototypal Inheritance
- Class-based Inheritance (ES6)
Prototype Chain
Every object in JavaScript has a prototype, which is another object. When you try to access a property or method on an object, JavaScript first checks the object itself. If it doesn't find the property or method, it looks up the prototype chain until it finds it or reaches the end of the chain.
let animal = { eats: true }; let rabbit = { jumps: true }; rabbit.__proto__ = animal; console.log(rabbit.eats); // Output: true console.log(rabbit.jumps); // Output: true
Constructor Functions
Constructor functions are used to create objects with shared properties and methods. The new
keyword is used to create instances of these objects. The prototype
property of the constructor function is used to add methods and properties to all instances.
function Animal(name) { this.name = name; } Animal.prototype.speak = function() { console.log(this.name + ' makes a noise.'); }; let dog = new Animal('Dog'); dog.speak(); // Output: Dog makes a noise.
Prototypal Inheritance
Prototypal inheritance is the mechanism by which an object can inherit properties and methods from another object. This is achieved by setting the prototype of one object to another object.
let animal = { eats: true }; function Rabbit(name) { this.name = name; } Rabbit.prototype = animal; let rabbit = new Rabbit('White Rabbit'); console.log(rabbit.eats); // Output: true
Class-based Inheritance (ES6)
ES6 introduced the class
syntax, which provides a more familiar and cleaner way to implement inheritance. The extends
keyword is used to inherit from another class, and the super
keyword is used to call the parent class's constructor and methods.
class Animal { constructor(name) { this.name = name; } speak() { console.log(this.name + ' makes a noise.'); } } class Dog extends Animal { speak() { console.log(this.name + ' barks.'); } } let dog = new Dog('Rex'); dog.speak(); // Output: Rex barks.
Examples and Analogies
Imagine inheritance as a family tree:
- Prototype Chain: Think of it as a family tree where each generation inherits traits from the previous one.
- Constructor Functions: Think of it as a blueprint for creating family members with shared characteristics.
- Prototypal Inheritance: Think of it as a family member inheriting traits from their ancestors.
- Class-based Inheritance (ES6): Think of it as a more formal and organized way to create and inherit family traits.
Understanding inheritance is crucial for creating reusable and maintainable code in JavaScript. By leveraging inheritance, you can build complex applications with less code and more structure.