Skip to content

Prototypal inheritance in JavaScript

Posted on:May 10, 2023

Table of contents

Open Table of contents

Intro

JavaScript doesn’t use classical inheritance, there is no concept of classes acting as a blueprint for creating objects in JavaScript. Instead, it uses prototypal inheritance. In prototypal inheritance, an object inherits properties from another object via the prototype linkage.

Syntax

child.__proto__ = parent;

[[Prototype]]

The double square brackets that enclose [[Prototype]] signify that it is an internal property, and cannot be accessed directly in code.

To find the [[Prototype]] of an object, we will use the Object.getPrototypeOf() method.

let vehicle = {
  drive: true
};
let tesla = {
  electric: true
};

tesla.__proto__ = vehicle; // sets tesla.[[Prototype]] = vehicle

Prototype Chain

Prototypal inheritance uses the concept of prototype chaining. This concept is used when searching our code. When we need to find a property in an object, it is first searched for in the object, and if not found, it is searched for on that object’s prototype.

Class Syntax

The class was added in the ES6 specification that was released in 2015. It is considered a syntactic sugar layered on the current prototype-based inheritance.

class Person {

  constructor(name, job, hobby){
    this.name = name;
    this.job = job;
    this.hobby = hobby;
  }

  getName() {
    return this.name
  }
}

let mark = new Person("Mark", "Graphic Designer", "Traveling")

Outro

Prototypes and prototypical inheritance are commonly used in many web application frameworks to allow sharing of common behavior and state among similar components. JavaScript is built with prototype inheritance at its core.