My Development Notes

Programming Made Easier


What is a Constructor Function in JavaScript

A constructor function is a type of function which creates a new object in JavaScript. Unlike other functions, the name given to a constructor function starts with capital letter, i.e., we have to use the pascal notation in its naming convention. Also this keyword is used to set the properties in constructor functions.

Let’s explain this with an example :

function NewProcessor() {
  this.name = "Intel i9 12th Gen";
  this.cores = "sixteen";
  this.threads = 64;
}

The example above is a constructor function. Notice how the function starts with a capital letter. Also, the properties are declared starting with the this keyword.

Now let’s say you run the above function. You’ll notice that it won’t run of itself. In order to make the above code work, you have to add the following code underneath the above constructor function :

let myNewBuild = new NewProcessor();

myNewBuild;

//  outputs NewProcessor {name: 'Intel i9 12th Gen', cores: 'sixteen', threads: 64}

What we’ve done is that we have used the new operator to call the constructor NewProcessor.

In a constructor function we have to use the new operator in order to make the this keyword to point towards the newly created object and run the function properly without any errors.


Posted

in

by

Tags:

Leave a Reply