Prototype and Prototypical Inheritance

Prototype and Prototypical Inheritance

·

2 min read

Whenever we create an object the Javascript engine automatically attaches your object with hidden properties and functions, the object is accessed via proto within every object that points out (references) the prototype that has been set for that object.

image.png

We can access the properties of the object through the dot operator and can use this property or even update the existing properties

image.png

, and with function when we create a function in JavaScript, the JS engine adds an extra property called prototype to the created function. This prototype property is an object (called a prototype object) that has a constructor property referenced to it by default and inside the prototype property, you will get access to proto object.

carbon (1).png

In JavaScript, any function can be attached to an object in the form of a property. An inherited function acts just like any other property and when an inherited function is executed, the value of this points to the inheriting object, not to the prototype object where the function is an own property.

All objects in javascript are references to an object and that object has a prototype of its own and this chain goes on till it is referenced to a null

We can get and set propertytype by Object.getPrototypeOf() and Object.setPrototypeOf(), as well as with non standard proto property. While modifying a prototype you might even come across warnings like

image.png

This is because when navigating through a property object, we basically hop from an object to its [[prototype ]] then its object [[prototype]] until we reach the end of the chain to null. In ES6, there were ways introduced to mutate [[prototype] but they harm the performance in all modern javascript engines. When you set proto, we reduce the future optimizations from Ion on that object, but you also force the engine to go crawling around to all the other pieces of type inference, which involves further deoptimization.

Changing the prototype of an object in the middle of execution is really not a good practice and cause huge performance issue.