DEV Community

Cover image for What is Prototype and how it works in constructor functions?
ainaperez
ainaperez

Posted on

What is Prototype and how it works in constructor functions?

hey there 👋, I'm Aina a web development student on my way to become a full-time developer.

In this article I'm offering an explanation of Object.prototype and why it is important when working with constructor functions.

Enjoy!

Context

In the beginning of my studies with Javascript, I was completing an exercise from my professors where I had to build a constructor function with certain properties and create two objects from that constructor function. This exercise was part of a bigger project where we had to create a Formula 1 viewer that displayed the results of races in a table format (you can find the project here).

In that exercice there were some build tests that we had to pass in order to complete the project.

My first version of the constructor function was this:

function DriverFn(givenName, familyName, dateOfBirth) {
       this.name = String(givenName + ' ' + familyName);
       this.dateOfBirth = new Date (dateOfBirth);
       this.getYearOfBirth = function(){
         return Number(this.dateOfBirth.getFullYear());
       }
}
Enter fullscreen mode Exit fullscreen mode

And then I created two objects using that function.

var x = new DriverFn('Lewis', 'Hamilton', '1985-01-07');
var y = new DriverFn('Michael', 'Schumacher', '1969-01-03');
Enter fullscreen mode Exit fullscreen mode

When console logging the data, for example with x.getYearOfBirth, I was getting everything correctly, but surprisingly the tests weren’t passing.

When checking the reason, I saw that the tests were built to expect the use of prototype.

And at that moment I wondered why would I use prototype if it works perfectly with only this?🤔

The use of Constructor functions and how they look when using this

The purpose of using constructor functions is to be able to make many different objects from one function. Sometimes it can be only 10 objects but surely on many occasions there will be many more, perhaps hundreds or thousands. This creates a lot of code and memory usage, so another goal we need to achieve with constructor functions is to minimize code duplication.

Having said that, first I'll show you a picture of how the objects look when we use this. I am going to use the live tool from Python Tutor to show you the data structure:

Code seen on Python Tutor showing how it is structured when we use this

With the keyword this, what we do is bind the properties directly into the object itself. That means that everytime we create an instance from DriverFn, we will get an object with its own name, its own date of Birth and its own method getYearOfBirth with the code of the function.

In our case, it's fine that each object has its associated name and date of birth, as they are different in every driver. But, we really don't need to have the function that allows us to know the year of birth duplicated in each driver, as it is the same code for all.

Now is when Prototype is useful to us.🤫

Using prototype in constructor functions

By itself, all objects have an associated protoype. If you went to the console with the previous code, and created an object, you would see the object with all the properties and then a "proto" property, which in the case of the Driver object is empty.

In order to include properties in the protoype (proto), we use the syntax:

Function.prototype.property = value;

So our function will look like this:

function DriverFn(givenName, familyName, dateOfBirth) {
    this.name = String(givenName + " " + familyName);
    this.dateOfBirth = new Date (dateOfBirth);
    DriverFn.prototype.getYearOfBirth = function(){
          return Number(this.dateOfBirth.getFullYear());
        }
}
Enter fullscreen mode Exit fullscreen mode

As you can see, we changed this in the method getYearOfBirth for DriverFn.prototype.

From now on getYearOfBirth won’t be stored in the object directly but in its prototype.

Code seen on Python Tutor showing how it is structured when we use prototype

As seen here, a constructor function has been created, with a prototype pointing to the getYearOfBirth function.

When creating new instances of the object, they will have their own properties of name and dateOfBirth, but then the method will be connected, inside proto, directly with the first getYearOfBirth that we have added to the constructor function, without the need to copy all the code of the function again.

This saves us a lot of memory space and load time, especially if we have thousands of objects with much more elaborate methods or properties.

What we have achieved here is based on the basic function of prototypes, which is to allow some objects to access the properties of others without having to define those properties every time we create an object.

That’s what we call Prototype Inheritance.

An introduction to prototype inheritance

As we said, prototype inheritance in Javascript is the ability of objects to access properties of other objects.

A simple example to explain this prototype inheritance is with Arrays:

When we create an array, we know that we can access many methods to manipulate it. Some of these methods can be: .length(), .indexof(), .reverse() etc.

Actually, we have never defined these methods in our code so how can we possibly access them? This is thanks to protoypes.
When we create a new object, array, function etc in Javascript, Javascript automatically creates, without our knowledge, a base object with all these methods that we can't see. In the case of arrays, the object created by Javascript is arr.proto (This is the first step in the chain, although we can go further until we reach the root of the root, which will not have any properties).

Therefore, every time we create an array, we can automatically access these methods without having to create all the code with all the methods in our array. This array, with all its ancestors, forms what is called a “chain of prototypes”.

In the case of our DriverFn object, which is a function, all the objects we create will inherit (that is, we will be able to access), the method and properties of the DriverFn constructor function, but also of the function.proto prototype object, which has its own properties and own methods, without the need to duplicate all the code over and over again.

Summary

  • Prototype is the Javascript method that allows objects to access properties of other objects.

  • Protoype is also very useful to reduce code volume and decrease loading times.

  • From a child element we can access properties stored in their parent's proto. Not only their direct parent, but also the grandparent and so on until we reach the end of the prototype chain, that will have a prototype of null.

Here ends my explanation of Prototype in constructor functions. A bit longer than what I intended initially but I hope it will be of use to whoever needs it!

At the beginning I didn’t understand Prototype as well and had to do quite a bit of research to get the good meaning of it, so don’t give up if you are in the same situation!.

As always, let me know in the comments your thought and if you have any further questions :)

Top comments (0)