What is a Prototype in JS
In this article, we’ll see what is a prototype in JS. I think you already know how to create objects to access the methods of a class. You can easily create functions inside a class but this article will show you how to create functions outside a class using the prototype.
Example of using a prototype
1. Creating a class
In the below code, we have created a class “person” and inside it we’ve created a constructor that assigned this.firstName to firstName and this.lastName to lastName. Then we’ve created the function getFullname() to display.
class person{
constructor(firstName, lastName){
this.firstName = firstName
this.lastName = lastName
}
getFullname() {
return this.firstName +" "+ this.lastName
}
}
2. Create object
This step creates the object for the class “person
” and checks the working functionality of the class
let p1 = new person("Roman", "Reigns")
console.log(p1.getFullname()) // Roman Reigns
3. Create a function outside a class using a prototype
To create a function using prototype for outside a class, we need to follow this syntax:
Syntax:
Example
person.prototype.printInfo = function(){
return `This Output is from prototype function = ${this.firstName} ${this.lastName}`
}
4. Accessing the prototype function using object
We have already created the object called p1 for the person class, so we can’t create another one to execute this prototype function. We can log the function name “printInfo
()” using “p1” object like:
console.log(p1.printInfo())
Output:
This Output is from prototype function = raj kumar
We can declare not only function but also a variable like this using prototype.
const marks2 = [83, 21, 35,32, 53];
console.log(marks2.sum()) //224
Creating a custom function in the array class
Here we have put students in an array, we will create a normal function as usual to find its sum value.
const marks = [80, 90, 68, 39, 29];
But if you want to find sum of multiple arrays you need to create a custom function using a prototype in arrayclass.
Array.prototype.sum = function(){
total = 0;
this.forEach(m=>{
total += m
})
return total
}
console.log(marks.sum()) //306
You can also find the sum values of another array like:
const marks2 = [83, 21, 35,32, 53];
console.log(marks2.sum()) //224
Conclusion
Prototypal inheritance is a powerful and flexible way to create relationships between objects and share properties and methods. While modern JavaScript provides alternative ways to work with prototypes, like classes and the extends
keyword, understanding the underlying prototype mechanism can help you better grasp the language and make more informed design decisions when building JavaScript applications.