Class vs Constructor


what is the different between class and constructor?


This is a great question and a huge source of confusion in my own learning. Nomenclature in programming is tough, because something will often have different means between languages.

In the context of JavaScript, it is confusing, because these ideas overlap a bit. For example, here is what I would call an object constructor in JavaScript:

function Person (name) { = name;

But, this thing could also be thought of as a class when taken in different perspective.

var p1 = new Person("Tess");
var p2 = new Person("Loren");

In this last example, we clearly instantiate Person objects using the Person object constructor. Really the object constructor is simply a function that is run when we make that object. We just often declare the constructor when we are declaring the type or the class of that object ( see Person constructor).

To clarify in JS terms, a class conceptually represents the blueprint of an object. This blueprint is tightly connected with the constructor which is simply a function that runs when we create(instantiate) an object of that class. It is tightly connected because we are making both the class and the constructor at the same time. Another example:

function Fruit() {}
Fruit.prototype.Eat = function() { console.log("yum");}

That is weird...the constructor is nothing. It is just an empty function. In this case, we can start to see the difference. When I instantiate a fruit object, like this:

apple = new Fruit();

JavaScript is instantiating an object of the Fruit class and calling the constructor function of that object. But the Fruit class contains more than just a constructor. It has a signature that is special and that is why it is a fruit. Only the Fruit class can create objects that have the .Eat() method.

Constructors have purposes and can be very useful. Often we use them to initialize properties in the object. But definitely not limited to that. But we can just as well have classes that instantiate objects with an empty constructor, but have other methods and properties.

Now just to be clear, JavaScript doesn't actually use classes in the typical sense (historically, JavaScript uses prototyped-based inheritance exclusively), because a class usually suggests other behavior that I did not talk about. I think there may be a class keyword with ES6, but I don't know much about it. The ideas are really similar though, and if you were to go to another language like C++ or C#, these ideas would also transfer over.