Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 15, 2021 10:50 pm GMT

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.
Image description

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

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To