JavaScript Prototypes

Javascript prototypes is used to define properties and methods that can be accessed by all the instances of the object.

In Javascript, every function and object has a default property known as the prototype. Let us understand it with the help of an example.

Source Code

          
            function Person(name, age, job) {
  this.name = name;
  this.age = age;
  this.job = job;
}
const person = new Person("Smith", 26, "web developer");
// checking the prototype value
document.write(Person.prototype); // { ... }          
        
Try it now

Code Explanation

In this example, we are trying to access the prototype of a Person constructor function. Here, prototype of Person constructor function is empty object { }.Since we do not assign any value to the prototype.

Prototype Inheritance

Javascript prototype is basically used to add properties and methods to the constructor function so that objects can inherit properties and methods from the prototype.

Adding Properties To The Constructor Function using Prototype

Following is the general syntax to add the property to an object constructor function:

General Syntax
      objectConstructorName.prototype.key = 'value';
    
Try it now

Source Code

          
            // constructor function
function Person(name, age, job) {
  this.name = name;
  this.age = age;
  this.job = age;
}
// creating objects
const person1 = new Person("smith", 25, "developer");
const person2 = new Person("ankita maurya", 26, "non tecthnical job");
// adding property to constructor function
Person.prototype.education = "graduation";
// prototype value of Person
console.log(Person.prototype);
// inheriting the property from prototype
console.log(person1.education);
console.log(person2.education);          
        
Try it now

Code Explanation

In the above example, it is clear that person1 & person 2 inherit the property education from the prototype of the person construction function.

Adding Methods to a Constructor Function Using Prototype

Javascript object method can be added to a constructor function's prototype.

Source Code

          
            function Person(name, age, job) {
  this.name = name;
  this.age = age;
  this.job = job;
}
// adding a method to the constructor function
Person.prototype.userInfo = function () {
  console.log(`hello my name is ${this.name} and my age is ${this.age} and working in the field of ${this.job}`);
};
const person1 = new Person("ankita maurya", 29, "non technical field.");
const person2 = new Person("smith", 30, "graphics designer");          
        
Try it now

Code Explanation

In the above example, it is clear that the userInfo method is added to the constructor function prototype, and two objects namely person1 and person2 can access the prototype method userInfo.

Web Tutorials

JavaScript Prototypes
Html Tutorial HTML
Javascript Tutorial JAVASCRIPT
Css Tutorial CSS
Bootstrap 5 Tutorial BOOTSTRAP 5
Bootstrap 4 Tutorial BOOTSTRAP 4