DEV Community

Cover image for How to Use JavaScript Prototypes and Inheritance
Rowsan Ali
Rowsan Ali

Posted on

How to Use JavaScript Prototypes and Inheritance

JavaScript is a versatile and powerful programming language that supports object-oriented programming (OOP) concepts. One of the key features of JavaScript that enables OOP is prototypes and inheritance. Understanding how prototypes and inheritance work is crucial for writing efficient and maintainable JavaScript code.

If you're a developer or just starting out.
I recommend signing up for our free newsletter 'ACE Dev' .
It gets delivered to your inbox and includes actionable steps and helpful resources.
Join us now

In this blog post, we'll dive deep into JavaScript prototypes and inheritance, exploring how they work, why they are important, and how you can use them effectively in your code. We'll also provide practical code examples to help you grasp these concepts.

Table of Contents

  1. What are Prototypes?
  2. The Prototype Chain
  3. Inheritance in JavaScript
  4. Creating Objects with Prototypes
  5. Using Object.create() for Inheritance
  6. ES6 Classes and Inheritance
  7. Conclusion

1. What are Prototypes?

In JavaScript, every object has a hidden internal property called [[Prototype]]. This property is a reference to another object, known as the object's prototype. When you try to access a property or method on an object, JavaScript will first look for that property on the object itself. If it doesn't find it, it will look up the prototype chain until it finds the property or reaches the end of the chain.

Example: Accessing Properties via Prototypes

const person = {
  name: "John",
  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

const student = Object.create(person);
student.name = "Jane";

student.greet(); // Output: Hello, my name is Jane
Enter fullscreen mode Exit fullscreen mode

In this example, student is an object that inherits from person. When we call student.greet(), JavaScript first looks for the greet method on the student object. Since it doesn't find it there, it looks up the prototype chain and finds the greet method on the person object.

2. The Prototype Chain

The prototype chain is a series of links between objects that JavaScript follows when looking for properties or methods. When an object is created, it inherits properties and methods from its prototype. If the prototype itself has a prototype, the chain continues until it reaches an object with a null prototype.

Example: Prototype Chain in Action

const animal = {
  speak() {
    console.log(`${this.name} makes a sound.`);
  }
};

const dog = Object.create(animal);
dog.name = "Rex";

dog.speak(); // Output: Rex makes a sound.
Enter fullscreen mode Exit fullscreen mode

In this example, dog inherits the speak method from its prototype, animal. When dog.speak() is called, JavaScript looks up the prototype chain and finds the speak method on the animal object.

3. Inheritance in JavaScript

Inheritance in JavaScript is achieved through the prototype chain. When you create an object that inherits from another object, the new object gains access to the properties and methods of the parent object.

Example: Basic Inheritance

const car = {
  wheels: 4,
  drive() {
    console.log("Driving...");
  }
};

const tesla = Object.create(car);
tesla.autopilot = true;

console.log(tesla.wheels); // Output: 4
tesla.drive(); // Output: Driving...
Enter fullscreen mode Exit fullscreen mode

Here, tesla inherits the wheels property and drive method from the car object. The tesla object also has its own property, autopilot.

4. Creating Objects with Prototypes

There are several ways to create objects with prototypes in JavaScript. One common way is to use the Object.create() method, which creates a new object with the specified prototype.

Example: Using Object.create()

const personPrototype = {
  greet() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

const john = Object.create(personPrototype);
john.name = "John";

john.greet(); // Output: Hello, my name is John
Enter fullscreen mode Exit fullscreen mode

In this example, john is created with personPrototype as its prototype. The greet method is inherited from personPrototype.

5. Using Object.create() for Inheritance

Object.create() is a powerful method that allows you to create a new object with a specific prototype. This is particularly useful for implementing inheritance in JavaScript.

Example: Implementing Inheritance with Object.create()

const animal = {
  speak() {
    console.log(`${this.name} makes a sound.`);
  }
};

const dog = Object.create(animal);
dog.name = "Rex";
dog.bark = function() {
  console.log(`${this.name} barks.`);
};

dog.speak(); // Output: Rex makes a sound.
dog.bark(); // Output: Rex barks.
Enter fullscreen mode Exit fullscreen mode

In this example, dog inherits the speak method from animal and also has its own bark method.

6. ES6 Classes and Inheritance

ES6 introduced the class keyword, which provides a more familiar syntax for creating objects and implementing inheritance. Under the hood, ES6 classes still use prototypes, but the syntax is more intuitive for developers coming from other programming languages.

Example: Using ES6 Classes

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  constructor(name) {
    super(name);
  }

  bark() {
    console.log(`${this.name} barks.`);
  }
}

const rex = new Dog("Rex");
rex.speak(); // Output: Rex makes a sound.
rex.bark(); // Output: Rex barks.
Enter fullscreen mode Exit fullscreen mode

In this example, Dog extends Animal, inheriting its speak method. The super() function is used to call the constructor of the parent class.

7. Conclusion

Understanding JavaScript prototypes and inheritance is essential for mastering the language and writing efficient, maintainable code. Prototypes allow objects to inherit properties and methods from other objects, enabling code reuse and modularity. Whether you use Object.create() or ES6 classes, the underlying mechanism is the same: the prototype chain.

If you're a developer or just starting out.
I recommend signing up for our free newsletter 'ACE Dev' .
It gets delivered to your inbox and includes actionable steps and helpful resources.
Join us now

By leveraging prototypes and inheritance, you can create complex object hierarchies and build robust applications. As you continue to explore JavaScript, you'll find that these concepts are fundamental to the language and are used extensively in modern JavaScript frameworks and libraries.

Happy coding! 🚀

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay