For the most part, object oriented programming is viable for advance or large projects. It helps make your code become clean, reusable, and more robust. Objects don’t execute right away. You have to call it and the order in which you run it depends entirely on you.’
Let’s learn how to create our own objects!
It’s not mandatory, but it’s proper practice to place your classes in a separate file. In your js folder, create a folder called classes. Inside this folder create a file called car.class.js. You don’t have to give your class file the .class, but it’s helpful to know which files are classes and which aren’t.
Lastly, let’s include this class in our HTML document so our script can use it. Add this line of code BEFORE you include your script.
In your class, add this bit of code.
You’ll notice that creating an object is almost like creating a function. The thing is, a function can be just a function or an object. It’s totally up to you! We’ll be using our function as an object.
Now, in order to use this object, we have to create an instance out of it. So, in your script, add this line of code.
var honda = new Car();
Just like that, you have now created an instance out of your Car class. The Car() function is now being used as an object. You can now access the properties and methods of the Car class, but the Car class doesn’t have any methods or properties.
There are actually more than one way to create classes. This is one of the most common methods of doing so. This method we used here is called the constructor function. It’s called that because we’re constructing our class inside a function. Pretty simple, eh? In our next tutorial, we’ll learn how to add properties and methods to our class. It’s very simple and straightforward.