Friday, April 10, 2020
Home Javascript What is Prototype in JavaScript?

What is Prototype in JavaScript?




The prototype is an object that is associated with every functions and objects by default in JavaScript, where function’s prototype property is accessible and modifiable and object’s prototype property (also known as attribute) is not visible.

JavaScript is a dynamic language, in which we can add new properties to the objects at any time. Let us see an example:

In the above example, the age property is attached to studentObj1 instance. However, studentObj2 instance will not have age property because it is defined only on studentObj1 instance.

How can you add more properties to the function that can be shared among the instances?

You can do it, by using Prototype. As we have already discussed in the first paragraph, every function includes prototype object by default. The prototype object is special type of enumerable object to which we can attach additional properties can be attached to it which will be shared across all the instances of it’s constructor function.

So, we can use the prototype property of a function in the above example in order to have age properties across all the objects as shown below.

Every object which is created using literal syntax or constructor syntax with the new keyword, includes __proto__ property that points to prototype object of a function that created this object.

Uses of Prototype

Basically, we use the prototype object in JavaScript for two things;

  1. To find the properties and methods of the object.
  2. To implement inheritance in JavaScript

Here, we created two Objects Person1 and Person2 using constructor function Person, when we called Person1.calculateAge() and Person2.calculateAge(), First it will check whether it is present inside Person1 and Person2 object, if it is not present, it will move Person’s Prototype object and prints the current age, which shows Prototype property enables other objects to inherit all the properties and methods of function constructor.

I will keep updating this article regarding JavaScript Prototype, Stay tuned with me for more articles.


Please enter your comment!
Please enter your name here

Subscribe to our newsletter

Snehasish Nayak
I am Snehasish Nayak, a Senior Programmer at NIC, Bhubaneswar and a Google Product Expert.

Recent posts

Recent comments