DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Asraful Islam
Asraful Islam

Posted on

What is a Prototype in JavaScript?

PropTypes: In JavaScript, a prototype is a technique by which JavaScript objects inherit properties or features from one another. JavaScript is also known as a prototype-based language. An object has a prototype object which has another prototype object and thus it continued until there is no prototype. This nature is known as the prototype chain.
For example:

function Person(first, last, age, gender, designation,skills) {

  // property and method definitions
  this.name = {
    'first': first,
    'last' : last
  };
  this.age = age;
  this.gender = gender;
  This.designation = designation;
  //...see link in summary above for full definition
}
Enter fullscreen mode Exit fullscreen mode

We’ve created an object instance like this:

let person1 = new Person('Asraful’, 'Islam', 28, 'male', β€˜Developer’,['React, Javascript']);
Enter fullscreen mode Exit fullscreen mode

Image description

In the image, you can see that if we write person1. We will see there are more properties than we declared in the Person object. Here first, last, age, gender, designation, skills are for the inheritance of the Person’s prototype object, and the other properties are for the inheritance of the Object’s prototype object.

Understanding prototype chain:
If we want to check the value of person1.age, it will simply return the result of the age 28. Because age is the prototype object of person1. Person1 is inheriting the properties of the object Person.

But if we want to check the result of person1.toString which is directly not inheriting from the Person prototype object. Then what will happen?
Well, in that case first it will check the prototype of person1 object. If it is found then simply run it. In this case, it will not be found in the person1 prototype object. Then it will check the prototype object’s prototype object to get the property β€œtoString”. Then it will find and return the result. This nature is known as the prototype chain.

Example:

person1.toString()
// 28
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Hi!I'm Noah!

Hey, my name is Noah and I’m the one who set up this ad!


My job is to get you to join DEV, so if you fancy doing me a favor, I’d love for you to create an account.
Β 
If you found DEV from searching around, here are a couple of our most popular articles on DEV: