Prototypal inheritance in JavaScript is a way for objects to inherit properties and methods from other objects. Unlike classical inheritance (like in some other programming languages), where classes inherit from classes, JavaScript uses a prototype chain where objects inherit directly from other objects.
Key Concepts
1. Prototype
Every JavaScript object has a prototype, which is also an object. This prototype can have properties and methods that the object can use.
2. Prototype Chain
If an object doesn’t have a property or method, JavaScript looks for it in its prototype. If not found there, it checks the prototype’s prototype, and so on, until it reaches null.
Example 1: Basic Prototypal Inheritance
Let’s start by creating two objects, where one object inherits from another:
// Creating a 'Person' object
const person = {
firstName: "John",
lastName: "Doe",
sayHello: function() {
console.log("Hello, " + this.firstName + " " + this.lastName);
}
};
// Creating a 'student' object that inherits from 'person'
const student = Object.create(person); // student inherits from person
student.firstName = "Alice";
student.lastName = "Smith";
// Now we can use the inherited method and properties
student.sayHello(); // "Hello, Alice Smith"
Explanation
Object.create(person)creates a new object,student, that haspersonas its prototype.studentgets properties and methods fromperson, so when we callstudent.sayHello(), it uses thesayHellomethod fromperson.
Example 2: Using Constructor Functions
In JavaScript, you can also use a function (called a constructor) to create objects that inherit from a prototype.
// Constructor function for creating a 'Person'
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
// Adding a method to the 'Person' prototype
Person.prototype.sayHello = function() {
console.log("Hello, " + this.firstName + " " + this.lastName);
};
// Creating a new instance of Person
const person1 = new Person("John", "Doe");
person1.sayHello(); // "Hello, John Doe"
// Creating another instance
const person2 = new Person("Alice", "Smith");
person2.sayHello(); // "Hello, Alice Smith"
Explanation
- The
Personfunction acts as a constructor. Person.prototype.sayHellodefines a method on all objects created byPerson.- Both
person1andperson2can accesssayHellobecause it’s part of their prototype (inherited fromPerson.prototype).
Example 3: Inheritance with Subclasses (Constructor Functions)
We can extend one constructor function to inherit from another constructor function, just like subclasses.
// Parent constructor
function Animal(name) {
this.name = name;
}
Animal.prototype.makeSound = function() {
console.log(this.name + " makes a sound");
};
// Child constructor (inherits from Animal)
function Dog(name, breed) {
Animal.call(this, name); // Call the parent constructor
this.breed = breed;
}
// Inherit methods from Animal
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
// Add a method to Dog
Dog.prototype.bark = function() {
console.log(this.name + " barks");
};
// Create a new Dog instance
const myDog = new Dog("Buddy", "Golden Retriever");
myDog.makeSound(); // "Buddy makes a sound"
myDog.bark(); // "Buddy barks"
Explanation
Animal.call(this, name)calls the parent constructor (Animal) from within the child constructor (Dog).Dog.prototype = Object.create(Animal.prototype)makes sure thatDoginherits methods fromAnimal.- Now
myDogcan use bothmakeSound(fromAnimal) andbark(fromDog).
Summary
- Prototypal inheritance is when objects inherit properties and methods from other objects.
- Every object in JavaScript has a prototype, and it can access properties and methods from that prototype.
- You can create inheritance chains using
Object.create(), constructor functions, andprototype.
This gives objects the ability to share behaviors without needing to duplicate code!
