Prototype chaining in Javascript

Ankita Panigrahi
2 min readMar 5, 2021

What is a prototype?

Javascript is considered as a prototypal language which means that we can inherit methods and properties from the object which will act as a template.

function Person(first, last, age, gender, interests) {
this.name = {
'first': first,
'last' : last
};
this.age = age;
this.gender = gender;
}
let person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);

The new keyword tells us that the Person is not a regular function, it’s a constructor function meaning make a new object and assign that object to the keyword this.

We can access the properties of person1 by person1.name, person1.age, etc.

But if we see all the properties of person1 in a console, we would see person1.valueOf(), person1. toString(), person1. hasOwnProperty(). So from where all these are coming from.

So person1 inherits from Person which in itself inherits the property of Object.

This is basically prototype chaining.

With every property requested in person1, the browser will check if person1 has the property. If yes then evaluate it. If no, then it will go one level up and check whether, its prototype object, Person has the property. If yes execute it. If not it will go to the last level, that is, Object(Person’s prototype object)

So methods like valueOf() or toString () are defined on Object.prototype

If you like the article please click on the clap. You can also follow me on Wordpress

--

--