What is a constructor in programming?

707 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

A constructor is a function that is automatically called when an object is created. Each class has its own constructor.

Say there’s a Car class. When I make a new car, I probably want to specify what kind of car I want, like what color, what make, etc. Then I can make a new car with `new Car(“blue”, “Honda”, …);`.

That sure looks like a function call, right? Well, it is. You make a new object belonging to the Car class, and the Car class automatically pipes those parameters to the constructor function you specified in the definition of Car – usually, to set some properties of the object depending on what parameters you passed in.

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