JavaScript Prototype Explained With Examples !!!

JavaScript is a prototype-based language. Being a javascript practitioner, one needs to know how prototype-object works in javascript.This article will give you an short overview of Prototype Object. Before reading this article, it is expected to have a descent understanding about object and constructor functions.

Let's examine the following example :

function data(name, age) {
    this.name = name;
    this.age = age;
}
const d1 = new data("Nav", 18);

Observations: 1.PNG

The given function has properties viz name and age which were defined within the curly braces along with that by default there is prototype property attached to it. This Prototype property is basically an object(note that, in JavaScript, everything treated as object).This ptototype property is attached to every object as ObjectName.prototype We will Come back to know what exactly is _ proto__.

Now data.prototype can be considered as an object as a whole and we can attach additional properties with it as:

data.prototype.key = 'value' (key and value are something of your choice)

data.prototype.alive= true;

You can also add new methods to a constructor function using prototype. Thus All the properties defined this way are shared amongst all the instantiations. So no multiple copies are made.

2.PNG

It can be clearly seen that alive property becomes an prototype of data.

Facts: The forEach(), map(), filter(), .length, .............. This all numerous inbuilt methods are nothing but the prototype properties.(Here In This case, given examples are of Array.prototype)

_ proto _, What Does It Mean ?

This term is simply a reference to the prototype object from which the instance has inherited.On clicking over it(in Console), You will simply get the list of all the prototypes you have attached to your object.

Prototype Chaining

The prototype chain mechanism is simple: When you access a property p on object obj, the JavaScript engine will search this property inside obj object. If the engine fails to search, it continues searching in the prototype of obj object. If it still cannot find it there then it goes up in the heirarchy and check prototype object of Object function because all the objects are derived from Object in JavaScript. If after the search has finished, and nothing has been found the result will be undefined.

Why Prototypes:

1)Whatever be the number of instances of the object, multiple copies are not made. In-fact a single copy is shared amongst all the instances and thereby contributing towards memory consumptions.

2) To implement inheritance in JavaScript.

Summarizing, 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 (aka attribute) is not visible. Every function includes prototype object by default.

Thank You for Reading. :)