A Prototype is an object that acts as the built in property for any object in JavaScript. It’s represented by ‘__proto__‘ in browsers. Since it is an object, it has its own prototype which results in making a Prototype Chain. This chain ends when a prototype is null. To access the prototype of an object, the method ‘Object.getPrototypeOf()’ is used(Note: This method is not the prototype of the object but simply points to its prototype).
When a property needs to be accessed from an object, and if it’s not present in the object itself, it is searched for in the object’s prototype. If it is not found there, the prototype’s prototype is searched. The chain is traversed till the property is found or prototype is null(in which case, undefined is returned). From this, it is evident that the scope of the object extends to its prototype object also.
‘Object.Prototype’ is the most basic prototype that all objects have by default. Its prototype is null. However, not all objects have ‘Object.Prototype’ as its prototype. For example:
1 | const currentDate=new Date(); |
An object created using ‘new Date()’ has the prototype ‘Date.prototype’. The prototype of Date object is ‘Object.Prototype’.
Modifying Prototypes
Any object’s prototype can be modified by adding a property, changing an existing property or by deleting an existing property. But it is generally considered to be a bad practice. Prototypes are global in nature, so it’s easy to get a conflict when modifying prototypes. If two libraries add a same method with different implementations, one implementation will overwrite the other.
In modern programming, modifying prototypes is approved only in one instance and that’s during polyfilling. Polyfilling is the term used, when substituting a method that exists in JavaScript specification that is not yet supported by a particular JavaScript Engine. The substitute can then be implemented manually without affecting the built-in prototype.