JS Prototypal Inheritance
In this page:
Basic Prototypal Inheritance
Prototypal inheritance lets one object reuse properties and methods from another object. Rather than copying method code onto every object, prototypal inheritance keeps one shared copy on the prototype and has each instance delegate lookups to it.
Example: Basic Prototypal Inheritance
const animal = { speak() { console.log("Some sound"); } };
const dog = Object.create(animal);
dog.speak();
Adding Child Properties
The child object can have its own properties while still using inherited methods. This lets you extend shared behavior for one specific instance without affecting the prototype other objects still rely on.
Example: Adding Child Properties
const animal = { speak() { console.log("Some sound"); } };
const dog = Object.create(animal);
dog.name = "Rex";
console.log(dog.name);
dog.speak();
Method Reuse
A shared method can work with different objects because this points to the object that calls the method. Because the prototype method is defined once, updating it changes the behavior for every object that inherits from that prototype, which is efficient but also worth being careful with.
Example: Method Reuse
const animal = {
speak() { console.log(this.name + " makes a sound"); },
};
const dog = Object.create(animal);
dog.name = "Rex";
dog.speak();
Changing the Prototype
You can create objects with a chosen prototype. Object.setPrototypeOf can also change a prototype, but it should be used carefully. Object.create(proto) is the direct way to build this relationship explicitly, giving you full control over exactly which object becomes the new object's prototype.
Example: Changing the Prototype
const proto = { greet() { return "hi"; } };
const obj = Object.create(proto);
console.log(obj.greet());
Practical Inheritance Example
Prototypal inheritance is useful when many objects need the same behavior without copying every method. This pattern predates JavaScript classes (which are largely syntax sugar over it) and still underlies how class-based inheritance actually works under the hood.
Example: Practical Inheritance Example
const vehicle = { drive() { console.log("Driving"); } };
const car = Object.create(vehicle);
const truck = Object.create(vehicle);
car.drive();
truck.drive(); // both share vehicle's method
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: