What is a constructor in programming?

713 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

If you have ever placed an online order (or kiosk order in person) for a fast food place, that’s a great way to think about a constructor. You tell it what kind of food item you want, and then specify the various options for it.

Give me a burger with 2 patties, 2 slices of American cheese, and pickles and mustard for toppings.

Burger would be the object here, and it would then have fields for number of patties, number of slices of cheese, a list of toppings. You the call the constructor like “new Burger(2, 2, {pickles, mustard})” and this submits the instruction to make a burger object with the specified parameters. This object can then be passed around and used as a unique instance of the class, and you can instantiate multiple objects of the same type without overwriting each other.

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