What is a prototype?
In JavaScript, a prototype is a fundamental concept that refers to a mechanism by which JavaScript objects inherit features from one another. Every JavaScript object has a "prototype" property that is a reference to another object. This referenced object can have its own properties and methods, which can be accessed by the original object. This prototype chain allows for properties and methods to be shared and reused across objects, providing a form of inheritance and resource efficiency in object-oriented programming in JavaScript.
Let's take an example of a simple object in JavaScript:
let x = {"name":"Rudra"} // We create a object x with a property name
let y = {} // We create a empty object y
y.__proto__.admin = true // We add a property admin to the prototype of y which is Object.prototype by default.
y.__proto__.admin // true
x.admin // true
We defined an object x which only has the property named name, later we created a new empty object named y and added a new property to it's prototype i.e. admin. Now, we can access the property admin from both the objects x and y. This is because of the prototype chain.
Since both the objects x and y are inheriting from the same prototype i.e. Object.prototype, they both have access to the property admin.
Thing to note:
- When you try to access a property of an object: if the property can't be found in the object itself, the prototype is searched for the property. If the property still can't be found, then the prototype's prototype is searched, and so on until either the property is found, or the end of the chain is reached, in which case undefined is returned. MDN
Prototype Pollution
The ability to inject new properties to a Object prototype is known as prototype pollution. Let's understand it with the example code that we discussed in the prototype section above.
We added a new property admin just to the prototype of y but what happens if we create a new empty object after we have modified the prototype? Let's see: let x = {"name":"Rudra"} // We create a object x with a property name
let y = {} // We create a empty object y
y.__proto__.admin = true // We add a property admin to the prototype of y which is Object.prototype by default.
y.__proto__.admin // true
x.admin // true
let abc = ""
abc.admin //true
This highlights that newly created object will also have the property of admin even though we didn't add it to the object itself. This is because of the prototype chain.