JavaScript Prototype
A prototype is an inbuilt object that its companies with functions by default, which can be affordable, adaptable, and invoke new variables and techniques to it and participate across all the representatives of its constructor function.
In JavaScript, a prototype is an object associated with any object created with a constructor function. A prototype object serves as a blueprint for an object that defines its properties and methods. It is used to add new properties and methods to all objects of the same type without adding them to every single object instance.
As we all know, JavaScript is a dynamic language where we can append new variables and techniques to an object at any point in time. Can there be a way that the new variable can be added to the function itself so that it’s accessible to all the objects created using the function?
The answer to this question is the use of a JavaScript prototype. We can affix a new variable or method to the object using the proto keyword. Now, let’s see some working executions of how to add new variables and methods using the JavaScript prototype functionality. There can be a time when we need to add new variables to a living object, which is nearly insolvable in other programming languages. But in JavaScript, we can attain this with the help of the prototype. It follows the succeeding syntax for adjoining a new variable: ClassName.prototype.variableName = value;
Let’s understand the operation of a JavaScript prototype to add a new variable with the help of the following illustration: