Classical inheritance vs Prototype delegation in JavaScript

Classical inheritance vs Prototype delegation in JavaScript

·

2 min read

In my previous posts, I have covered Class and Prototype in JavaScript and learned its behaviour and working. In this post, we're going to do an ultimate faceoff😂 Kidding. Just a simple post about Prototype vs Class Delegation in JavaScript.


Prototype

The prototype is a design pattern followed in JavaScript with objects inherits(references) the properties of another object. Almost all the objects have this prototype/prototype chain in them.

image.png

In the above example, we created a new object called media, and it has its own property greet() and also have inherited the native properties of an object under the key __proto__. This is called a prototype chain or objects linked to other objects.

image1.png

Now let's extend a new object sociaMedia from this media to visualize this chain. As you could see the newly created object socialMedia has __proto__ which references the media object's property, and this media object has a __proto__ which refers to the main object properties.

image2.png

Class

With the instruction of ES6 class, a lot of us had confused, what's the difference between class inheritance and prototype delegation (property term to define inheritance in JavaScript).

class Media {
    constructor() {
    }
    greet(name) {
            return `Welcome to ${name}`
    }
}
const media = new Media(); 
media.greet('RAHULISM'); // Welcome to RAHULISM

Class is just sugar for using the prototype. Under the skin, it used the prototype to achieve the concept of inheritance. Let's try the same class Media and see what it has internally.

As you could see internally Media has a proto for its method and within that, it references the main Object properties.

image4.png

Now if we extend this Media() and create a new class then that new class will have the same prototype chain as we saw above.

Class inheritance

image5.png

Though they seem to be similar, there is a minor difference, between the Class-based approach and the prototype-based approach.


Deep Dive?


Thanks For Reading😊

Did you find this article valuable?

Support Rahul by becoming a sponsor. Any amount is appreciated!