JavaScript Class Constructor And Prototype Object

Constructor Function,Prototype Object In JavaScript By Sagar Jaybhay

Class Constructor Function:

What is a constructor function and what it does?

Class Constructor is a function that creates an object class or the function that allows you to create multiple instances of a class very easily. Constructor function technically speaking is like a normal function but

  1. Class Constructor Function named with the capital letter first.- it is a best practice to write constructor function first name with a capital letter.
  2. Class Constructor Function should execute with the new operator.
function User(firstName,lastName,age,gender){
    this.firstName=firstName;
    this.lastName=lastName;
    this.age=age;
    this.gender=gender;
}

var user1=new User('Sagar','Jaybhay',30,'Male');

console.log(user1);

When a function is executed with new, it does the following steps:

  1. A new empty object is created and assigned to this.
  2. The function body executes. Usually, it modifies this, adds new properties to it.
  3. The value of this is returned.

Prototype object

How to use a prototype object with a constructor function?

A prototype is used with constructor function to add properties and function which turn associated with object which we created by using Constructor function.

Below is our constructor function

function User(firstName,lastName,age,gender){
    this.firstName=firstName;
    this.lastName=lastName;
    this.age=age;
    this.gender=gender;
}

we create the object by using constructor function.

var user1=new User('Sagar','Jaybhay',30,'Male');

Now we want to add email domain property to our constructor function and we are going to do this by below way.

User.prototype.emailDomain="@google.com";

In this email domain is available to all object we create.To access this use below code.

 console.log(user1.__proto__.emailDomain)
console.log(user1.__proto__.emailDomain)

 But if you want to access the property by using property you can directly use the property like below

user1.emailDomain

It means when you want to add property or function after constructor function declared and want all object get that property and function you can use the prototype to add function and property.

Class Constructor Function, JavaScript Class Constructor And Prototype Object, Sagar Jaybhay
Constructor Function and Prototype Object In JavaScript

Now by using prototype, we can add function to this constructor function. The syntax of this function is like below

User.prototype.getEmailInfo=function()
{
    return  this.firstName+"."+this.lastName+ this.emailDomain;
}

To get value if email id we use user1 object which is created above. And by using function name we call this and output we get

console.log(user1.getEmailInfo())
Sagar.Jaybhay@google.com

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *