Prototypes in JS

Prachi
3 min readSep 25, 2020
Photo by Halacious on Unsplash

Hello beautiful people 🌻! This article is all about Prototypes in JavaScript. The need for prototypes is described in my previous article JS Constructor Function, important to read this before you go through prototypes.

Whenever an object is created, the JS engine adds an internal property called prototype.

Prototype is simply an object that has a constructor property by default. The constructor property points back to the function where the prototype object is a property.👻

function Person(firstName, lastName) {
this.firstName = firstName,
this.lastName = lastName,
this.fullName = function() {
return this.firstName + “ “ + this.lastName;
}
}
let p1 = new Person(‘Harry’, ‘Porter’);
console.log(p1);

Let’s create another object for Person.⛄

let p2 = new Person(‘Ram’, ‘Pyare’);
let p3 = new Person(‘Shery’, ‘Labra’);
console.log(p2);
console.log(p3);

The interesting thing to mark here is the constructor property of the prototype object of both p1 and p2 is pointing to the same function i.e. Person. You can check it by comparing the __proto__ object of p1 and p2.

console.log(p1.__proto__ === p2.__proto__) //true

When we log Person.prototype we can see the constructor property is pointing to the same function Person that objects p1 and p2 is pointing🎃.It means

Person.prototype === person1.__proto__ //✅
p1.__proto__ === p2.__proto__ //✅

The prototype object of the constructor function is shared among all the objects created using the constructor function.😁

How to add properties in the prototype object?💭

As we know a prototype is an object and that is why we can add properties and methods to the prototype object. Let’s see how!

Person.prototype.role="Actor";
console.log(Person.prototype.role) //Output:Actor

But wait!😣 how to access the role property using objects p1 and p2.?? Remember we discussed above that the prototype object of the constructor function is shared among all the objects created using the constructor function.

console.log(p1.role); //Actor
console.log(p2.role); // Actor

Let’s add the method fullName in the prototype object.

function Person(firstName, lastName) {
this.firstName = firstName,
this.lastName = lastName
}
Person.prototype.fullName = function() {
return this.firstName + “ “ + this.lastName;
}
let p1 = new Person(‘Harry’, ‘Porter’);
console.log(p1.fullName())// Harry Porter

The method fullName is shared among the objects of the constructor function Person.

Thank You for reading this article!

--

--