What is a constructor in programming?

711 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 used to construct a new object of this class. I’m gonna assume that you know about what a class and an object as an instance of a class is based on how you worded the question, if not feel free to ask for a follow-up.

Let’s say you have a class rectangle. Every rectangle is defined by the two opposite corner points, so it doesn’t make any sense to have a rectangle without those two points. Your constructor for an rectangle object therefore takes two parameters and might check them for validity, e.g. not the same point twice etc.

This way, you can always ensure that your rectangle is valid and can e.g. be drawn to the screen.

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