What is a constructor in programming?

729 viewsOtherTechnology

I am still trying to wrap my head around the concept I learned in class a while ago. We learned briefly about constructors in JavaScript. Can someone please ELI5? Thank you!

In: Technology

18 Answers

Anonymous 0 Comments

When you create an instance of a class- “you create a variable of your own type” This is an object, which can have more than one attribute to it, more than one value assigned under a single name.

So if you are creating a new “variable of this type” and sending it some values, how will the compiler know which value goes to which attribute of the “multi variable”?

Simple, you just tell it. A constructor is a function that runs when you’re creating an object of the type of your class.
In this you can tell it which attribute gets which value.

But since it is just a function that’s being called when an object is created, why not have it do more than just assign stuff. You can also call some initialising functions of your own.

A good example of this is if you have a class rectangle. Now if you create a shape of this type (object instantiation), you will have to tell which value is the Length and which is the Width.

So you can create a constructor and use it to assign each of its attribute with these values. But that’s not all, you can also use the constructor to call a function that can take these values and calculate its area, and save it in another attribute Area.

All this when the object is created itself instead of manually going and assigning each object attribute.

You are viewing 1 out of 18 answers, click here to view all answers.