In my previous posts, I have covered Class and Prototype in JavaScript and learned its behavior 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.
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.
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.
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.
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
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๐
Top comments (4)
With private members classes are now more than just a sugar
JS classes are not โjust syntactic sugarโ
Also some things are natively implemented to be created via a
class
rather than a constructor function - so in the case of HTMLElement one has to use Reflect.construct() to create an instance from (transpiled) ES5.That said in JavaScript Classes are a template for creating objects - not classes in the sense of class-based object orientation where "class membership" remains static for the lifetime of the object.
welcome back
Yeas. Was posting on Hashnode daily lol.