JavaScript: The Function() Constructor

In javascript, we use a constructor function to create an object and use its properties in the future. A constructor function is always named with a capital letter.

Don't be confused this is very simple.

  • To create an object think of it as a class that can access its methods just like java.
  • But we create a constructor function with the 'this' keyword and will try to create an object for this function name and access the parameters provided.
  • This keyword is to be used to create a value using an empty object and try to access it outside the constructor by creating the object of the respective function name.

Example - Simple

function Marvel()
{
    this.captainAmerica = 'Steve Rogers'
    this.ironMan = 'Tony Stark'
}

const mar = new Marvel();

console.log(mar.captainAmerica)
console.log(mar.ironMan)

Output:

Steve Rogers
Tony Stark

Here we have created a function constructor named Marvel and added some information inside it with this keyword to create an object and access it. And as we discussed we have created an object of the function constructor name mar and via that object, we got the following information inside it.

Let us see another example with a constructor function that contains parameters.

Example - Parameters

function Marvel(Name, Status)
{
    this.Hero = Name
    this.status = Status
}

const mar = new Marvel('Steve Rogers', 'Alive');
const mar2 = new Marvel('Iron-Man','Deceased')

console.log(mar.Hero)
console.log(mar.status)

console.log(mar2.Hero)
console.log(mar2.status)

Output:

Steve Rogers
Alive
Iron-Man
Deceased

So here we can use parameters in function constructors too. We have created two parameters for the function Marvel and passed those parameters into the 'this' keyword empty object as the parameter name itself. When we are creating the object afterward we can give our input for the respective parameter and create multiple objects for the same parameter and access it too.

Fri, 10/22/2021 - 11:59

Authored by

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.
Tags