Javascript Prototypes

Created with getavataaars.com
Samir Ergaibi
2019-09-22
prototypes-poster

What are JavaScript prototypes?

In JavaScript inheritance is handled with prototypes. Even when you use ES6 classes, what is really going on under the hood are the workings of prototypes. And that's what we're going to try and understand in this post!

In a sense what a prototype really only is, is an object that sits on another object and can contain various properties or methods.

So to try and understand this better we can start by declaring an empty object in the browser and open it up.

Javascript Prototypes - image 1

But wait, the object doesnt seem to be empty?! There is this thing called __proto__ attatched to it. Well, that's the prototype!

All objects in JavaScript have a prototype and through it they inherit properties and methods. What we are looking at right now is Object.prototype which is the first link in the prototype chain and since it is the first link in the prototype-chain all objects in JavaScript will inherit it's properties and methods.

There are other prototypes which contain methods and properties aswell. When you create an array it inherits from Array.prototype and that is why you have access to all the different array methods like sort(), filter() forEach() ect.

Javascript Prototypes - image 2

In the same way when you create a Date object and get access to all of it's methods your date object is getting access to all of those methods through Date.prototype.

Javascript Prototypes - image 3

Strings and numbers follow the same pattern, when a string is created it inherits from the String.prototype and a number inherits from Number.prototype. In turn all of these object inherit from the Object.prototype that is the last prototype in the chain and inherits from null.

When an array method is called on an array, the called method doesn't actually live on the array but rather on the Array.prototype. That means that when a method is called on a array e.g. [ ].forEach( ) JavaScript looks on the array and when it doesn't find the forEach method it continues down the prototype chain onto the next prototype and looks there. Next in line is the Array.prototype so JavaScript looks there and finds it and runs it. That is pretty much how inheritance in JavaScript works with prototypes.

A visualization of the prototype chain might look something like this.

Javascript Prototypes - image 4

I hope that prototypes makes abit more sense now and thank you for taking your time and reading through this post.