background-shape
feature-image

ES6 introduced classes and inheritance. Until then javascript was following the way of prototypal inheritance. But under the hood ES6 still follows the way of prototypal inheritance.

What is Prototypal Inheritance?

Any object created in javascript is an instance of Object. And this will be reflected in the __proto__ property of the object.

1
2
3
4
5
var user = {
  name: "John",
};

console.log(user);

Console Output:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{
  name: "John"
  ▼ [[Prototype]]: Object
    ▶ constructor: f Object()
    ...
    ...
    ▼ __proto__: Object,
      ▶ constructor: f Object()
      ...
      ...
      ▶ __proto__: null
}

Prototypal Chain

This inheritance can be chained to n-th level. This is named an Prototypal Chain.

Difference between prototype and proto

In the above code we find [[Prototype]] as well as __proto__ property. [[Prototype]] is the property of a class constructor. __proto__ is the property of a class instance.

Let’s see with an example. Consider a user constructor, which has a property name and a method sayHi.

1
2
3
4
5
6
7
8
9
function User() {} // User constructor

User.prototype.name = "";
User.prototype.sayHi = function () {
  console.log("sayHi");
};

let user = new User(); // new user instance
user.prototype.name = "John";

Now let’s see the [[Prototype]] and __proto__ of the user instance.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  ▼ User {}
    ▼ [[Prototype]]: Object
        name: "John"
        sayHi: ƒ ()
        constructor: ƒ User()
        ▼ [[Prototype]]: Object
          ...
          ...
          ▼ __proto__: Object
            name: ""
            sayHi: ƒ ()
            ▼ [[Prototype]]: Object
              ...
              ...
              ▼ __proto__: Object
                constructor: ƒ Object()
                hasOwnProperty: ƒ hasOwnProperty()
                isPrototypeOf: ƒ isPrototypeOf()
                propertyIsEnumerable: ƒ propertyIsEnumerable()
                toLocaleString: ƒ toLocaleString()
                toString: ƒ toString()
                valueOf: ƒ valueOf()
                __proto__: null

Observing last but one proto, we can see that the __proto__ of the user instance is the Object constructor. This is because everything is an object in javascript.