Every object created using this method will have a copy of the properties and methods in the constructor functions.
Properties may differ from object to object but generally, methods are the same for all the objects. Therefore, it is not a good practice to have methods in constructor functions because a copy of the method will be created in every object. Therefore, it might consume memory space and will affect the performance when there are 1000s of objects. Therefore, we use a prototype to define the methods and common properties.
What is a prototype?
Every object in JS has a hidden property called __proto__ that points to its parent’s prototype. Therefore, all the object will get access to the Parent’s prototype object which consists of properties and methods. The prototype of the Parent Class points to the Prototype of the Object class and the prototype of the object class is null.
Adding methods and properties to Prototype
Calling methods in the prototype
It is similar to calling the methods in the objects. There is no any difference. The only difference is each object doesn’t have a copy of the method. So when you call a method from an object, the JS engine first checks whether the object has the method, if the method is not found then it checks for the method in the prototype, if it is found it will execute the method or else it will check whether the prototype of the Object class has the method if not it will return null.
From the above figure, it is evident that objects don’t have a copy of the properties and methods added to the prototype ( getName() method and salary property). Those methods and properties are common to all the objects of a class and can be accessed via the __proto__ property.