What is prototype and prototype chaining in JavaScript ?

What is prototype and prototype chaining in JavaScript ?

Prototype Chaining in JavaScript.

We have always seen that every object in JavaScript has some pre-defined methods. When I was using console.log() for an object in the browser console, that is when I first encountered the word “prototype” in JavaScript.

What is prototype ?

The prototype object is a particular type of enumerable object to which additional properties can be attached, which will be shared across all the instances of its constructor function.

A prototype is an object associated with every function and object by default in JavaScript.

Every function includes a prototype object by default.

The function's prototype property is accessible and adaptable and the object's prototype property is not visible.

You can see the prototype an object is pointing to using the proto property.

function Student() {
    this.name = 'John';
    this.gender = 'M';
}

Student.prototype.age = 15;

var studObj1 = new Student();
alert(studObj1.age); // 15

var studObj2 = new Student();
alert(studObj2.age); // 15

What is prototype chaining ?

Nearly all objects in JavaScript are instances of Object. That means all the objects in JavaScript, inherit the properties and methods from Object.prototype. This is called Prototype chaining. This is a very powerful and potentially dangerous mechanism to override or extend object behavior.

Objects created using new keyword, inherit from a prototype called Object.prototype.

For example: If a date object [new Date()] is created with new keyword, then it inherits the Date.prototype.
We have Date, Array, Function, RegExp in the list for the same, All these objects inherit from the Object.prototype.

When we try to access any property of an object it is first checked in the own property of the object.

f the property does not exist in the property, then the prototype object is scanned for that property. This continues until we get the property we are accessing or we reach the end of the prototype chain giving undefined.

// defining the constructor function
function Student(name,age){
    this.name = name;
    this.age = age; 
}
// creating an object instance of the Student
const student = new Student('John',32)

console.log(student)

Output

I hope you enjoyed and learned something new with the blog.💕