DEV Community

Muhammad Muhktar Musa
Muhammad Muhktar Musa

Posted on

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 object’s instances.

let us look at an example

let person = {}; = "David";
person.age = 45; = function() {
console.log(`person is eating`);
Enter fullscreen mode Exit fullscreen mode

Here we are creating new instances for the object. If you console.log this object you won’t 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 they’re 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 there’s 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).

Top comments (0)