An Interest In:
Web News this Week
- March 21, 2024
- March 20, 2024
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
Prototype in javascript
The prototype is an object that is associated with every functions and objects by default in JavaScript. Prototype property is accessible and modifiable and object's prototype property (aka attribute) is not visible. Every function includes prototype object by default. This allows you to define properties on objects that can be accessed via the objects instances.
let us look at an example
let person = {};person.name = "David";person.age = 45;person.eat = function() {console.log(`person is eating`);}
Here we are creating new instances for the object. If you console.log this object you wont see any methods, but you can use methods like set or get for the object prototype.
When you use map, JavaScript looks for map in the object itself. If map is not found, JavaScript will try to look for a Prototype. If JavaScript finds a prototype, it continues to search for map in that prototype.
So the correct definition for Prototype is: An object that instances can access when theyre trying to look for a property.
Prototype chain
When a property is accessed in javascript, javascript checks to see if the property is available inside the object. If yes, JavaScript uses the property straight away. If the property is not inside the object, JavaScript checks if theres a Prototype available. If there is a Prototype, repeat Step 1 (and check if the property is inside the prototype). If there are no more Prototypes left, and JavaScript cannot find the property, it does the following:
Returns undefined (if you tried to access a property).
Throws an error (if you tried to call a method).
Original Link: https://dev.to/mcube25/prototype-in-javascript-gjo
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To