Feels like Classes, Smells like Classes!
In the example bellow, we have defined class Car. Notice the difference between the function declaration and class declaration? While declaring a class, we do not use semicolon. Similarly, to define a constructor, use the keyword ‘constructor’ and add the parameters to set the initial properties. If you check the type of the class you will be surprised that it’s actually “function” not “class”.
If you inspect the newCar object in detail you would see similar structure when you create object with function constructor. The only difference is that the constructor displays the keyword “class”.
Simulating Class with Function Constructor
You can simulate the class behaviour using a function constructor wrapped inside an Immediately Invoked Function Expression (IIFE). This is obviously to see what is going on inside when you define a class.
Now let’s add a drive() method to class Car. Note that there is no comma between two methods. It feels weird if all you have used is JSON Objects.
Next, let’s build objects from class Car. The syntax is similar to what we used with function constructors, using the
new keyword. You can execute the method on this object by calling