In the above example, the age property is attached to studentObj1 instance. However, studentObj2 instance will not have age property because it is defined only on studentObj1 instance.
How can you add more properties to the function that can be shared among the instances?
You can do it, by using Prototype. As we have already discussed in the first paragraph, every function includes prototype object by default. The prototype object is special type of enumerable object to which we can attach additional properties can be attached to it which will be shared across all the instances of it’s constructor function.
So, we can use the prototype property of a function in the above example in order to have age properties across all the objects as shown below.
Every object which is created using literal syntax or constructor syntax with the new keyword, includes
__proto__ property that points to prototype object of a function that created this object.
Uses of Prototype
- To find the properties and methods of the object.
Here, we created two Objects Person1 and Person2 using constructor function Person, when we called Person1.calculateAge() and Person2.calculateAge(), First it will check whether it is present inside Person1 and Person2 object, if it is not present, it will move Person’s Prototype object and prints the current age, which shows Prototype property enables other objects to inherit all the properties and methods of function constructor.