What is a constructor in programming?

733 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

Let’s say you own a bakery, and one of the things you do there is make cakes to order.

Bad ways to do that:

Make each customer tell you *exactly* how to make the cake they want.

Have completely separate instructions for how to make every possible variant of every cake. I’m talking having one recipe for how to make a 3 tier chocolate cake with “Happy Birthday” on it and another recipe for a 3 tier chocolate cake with “Congratulations” on it.

Accept orders without checking them. If it turns out that the customer ordered something impossible or didn’t give you enough info they only find that out a while later and the explanation is super confusing.

Every customer gets the exact same cake (this one would be totally fine for other situations, just not this one.)

Good way to do that:

1. Customers get an order form to fill out.

2. The order form gets checked, and if there’s something wrong the customer is told immediately in a way that’s easy to understand. “You have to put the number of tiers you want,” “we only have blue, pink, or green icing, not yellow,” “you can only order a vanilla gluten free cake, not a chocolate one.”

3. If the order form looks good then it goes to the back (where the customer can’t see) and is made according to a procedure that branches based on stuff like how many tiers the cake is.

A constructor is sort of like that order form, the procedure for checking the order form, and the procedure for making a cake based on the order form.

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