Prototypes in JavaScript

Prototypes in JavaScript


Consider the constructor function below:
function Human(firstName, lastName) {
this.firstName = firstName,
this.lastName = lastName,
this.fullName = function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = new Human("Virat", "Kohli");
console.log(person1)

Let’s create objects person1 and person2 using the Human constructor function:
var person1 = new Human("Virat", "Kohli");
var person2 = new Human("Sachin", "Tendulkar");
On executing the above code, the JavaScript engine will create two copies of the constructor function, each for person1 and person2.

i.e. every object created using the constructor function will have its own copy of properties and methods. It doesn’t make sense to have two instances of function fullName that do the same thing. Storing separate instances of function for each object results in wastage of memory. We will see as we move forward, how we can solve this issue.

Prototypes

When a function is created in JavaScript, the JavaScript engine adds a prototype property to the function. This prototype property is an object (called a prototype object) that has a constructor property by default. The constructor property points back to the function on which prototype object is a property. We can access the function’s prototype property using functionName.prototype.

As shown in the above image, Human constructor function has a prototype property that points to the prototype object. The prototype object has a constructor property that points back to the Human constructor function. Let’s see an example below:

function Human(firstName, lastName) {
this.firstName = firstName,
this.lastName = lastName,
this.fullName = function() {
return this.firstName + " " + this.lastName;
}
}
var person1 = new Human("Virat", "Kohli");
console.log(person1)

Creating an object using the constructor function


When an object is created in JavaScript, JavaScript engine adds a __proto__ property to the newly created object which is called dunder proto. dunder proto or __proto__ points to the prototype object of the constructor function. 

If you enjoyed the article and want updates about my new article, please follow me

Comments