Prototypes in JavaScript

JavaScript is a Prototype based Object Oriented Programming language. There are various methods to create classes in JavaScript. One of the most used methods is using the constructor function method. The constructor function looks like a normal function but when we call this function, we use the new keyword to create objects. So, this function act as a class.

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?

Prototype is an object that is linked with every functions and objects by default in JavaScript. When a function is created in JavaScript, the JavaScript engine adds a prototype property to the function. This prototype contains methods that are accessible to all objects linked to that prototype. Prototypes can also have properties. The value of the properties defined in the prototype is the same in all the objects. Therefore, simply prototype can be used to add properties or methods to all existing objects of a given type or to an object constructor.

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.

3rd year Software Engineering Undergraduate