What is a constructor in programming?

715 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

The main idea behind object oriented programming is that data is inside objects that can only be changed through some operation that guarantee the object is valid all the way.

Imagine I give you two devices. One only has two buttons, Play music and Stop music.

The other has all kinds of visible wires, you can touch the wires with each other to do all kinds of things, including things that can break the device.

That is why, in object oriented programming, you can only interact with data in an instance through some operations that are called “public”. A well designed class should allow you to change things freely, but only through some operations that guarantee you can’t break it.

Now, you say, how do you guarantee that the first, initial state, of the object is a valid one? Well, through something called a constructor. You should think of a constructor as a function that creates a valid object of that class.

In JavaScript, well, things are weirder, but the idea is the same, a constructor is what allows you to build an instance of a class.

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