- A class is a description of how to create an object of a specific type.
- The constructor is the function that you call to make that object.
And it might be helpful to think of this
in the definition of the class as a placeholder for the object that will be created. So with your example, if you create a new
Vegetable, this
refers to that new vegetable object you just created, and that object has a property “name”.
class Vegetable {
constructor(name) {
this.name = name;
}
}
So there, you have a description of how to create that object. It will just have a property name
, so the thing you are creating looks like this:
{ name: /* whatever name you gave it */ }
The constructor function is just a JS function: it’s the thing you use to create the object. It is also where you can pass things in to configure how you want to create it, in this case you want to specify the name.
So
const carrot = new Vegetable("carrot")
Is saying "make a new object of the type Vegetable, assign ‘carrot’ to the object’s name
property, and assign that new object to a variable carrot
". The variable carrot
now refers to this thing:
{ name: "carrot" }
Note that this basically does the same thing:
function createVegetable (name) {
return { name: name };
}
The differences mainly come down to Object Oriented vs. Procedural programming styles. And note the most obvious difference is that when you add methods to classes (functions on the attached to the object), those methods get shared between all members of the class, and you can make child classes that inherit from parent classes and get access to all those methods.
edit: note that JS does not really have “classes” in the sense of other languages, the syntax here is just to make it look more like those other class-based languages (though the end result is much the same). So if you’re ever reading up on OO programming/class-based programming, be aware JS doesn’t work the same way