Understanding Prototypal Inheritance in JavaScript

Ellen Park
JavaScript in Plain English
3 min readMar 14, 2021

--

A brief overview designed to help you understand the fundamental concepts of prototypal inheritance.

Photo by Samuel Ferrara on Unsplash

What is Prototypal Inheritance?

In simple terms, prototypal inheritance refers to objects inheriting properties and methods from other objects. These object that properties are being inherited from are called prototypes. JavaScript is a prototype based language. It is not class based.

But wait! Doesn’t JavaScript have classes? If you’re familiar with JavaScript, most likely you’ve written something similar to this.

class Dog {
constructor(name, breed) {
this.name = name;
this.breed = breed;
}
}

Don’t let this fool you! Class syntax was introduced in ES6, however it is simply syntactic sugar. The above Dog class is the same as below.

function Dog(name, breed) {
this.name = name;
this.breed = breed;
}

What Exactly is a Prototype?

In JavaScript, objects inherit from other objects. Remember that functions are also objects. This can be confirmed by using typeof.

function dog {}typeof dog // “function”

When an object is created in JavaScript it will automatically have a property called prototype. This is the link connecting objects to one another, the chain in the prototype chain.

How Are Prototypes Used?

When you access a property on an object, the JavaScript engine will search for the property inside the object first. If the search fails, it will move on to the object’s prototype. This process will repeat until the property is found or until the end of the prototype chain is reached.

If you keep going up the prototype chain, eventually you’ll reach the top. At the very end is the base object. All objects (functions and arrays included) are created from the base object. For example, if you create an object using object literal then check the __proto__ property, it will point to the base Object.

Prototype Chain in Action

Let’s break down the code snippet below.

  1. First, we define our constructor function, Dog. On a side note, a constructor function is just a regular old function, but by convention it is named with a capitol letter first.
  2. Next, we add a function, bark, to the Dog prototype object. This means that all instances of Dog will have access to bark. Because bark is applied to the prototype not the instance, bark is stored in memory only once, reducing duplication.
  3. At line 10, we create our new Dog instance, spot. Finally, we invoke spot.bark(). Behind the scenes, the JavaScript engine is checking our spot object for a method called bark. It won’t find it. So, it’ll move up the prototype chain to spot.prototype, where it can find the method and invoke it.

--

--

Full Stack Software Engineer specializing in Javascript, React and Ruby on Rails