← Back to JavaScript Course | Chapter 7: OOP & Prototypes | Lesson 2 of 6

JS Prototypal Inheritance

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

javascript
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

javascript
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

javascript
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

javascript
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

javascript
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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.