Hello, Explorer! Today, we're unveiling a core concept of Object-Oriented Programming (OOP): JavaScript classes. These classes act as blueprints, allowing us to generate objects — instances
of these blueprints — each carrying unique properties and behaviors. This lesson has one aim: to understand what classes are, how to create them, and their purpose within your JavaScript code.
Think of a JavaScript class as a construction blueprint. By following the blueprint, we can create specifically structured objects, each filled with different values.
Here, Fruit
is our blueprint or class. This blueprint then enables us to generate a variety of fruit objects with specialized attributes, much like constructing a building.
Creating an instance of a class, essentially bringing an object to life from this blueprint, uses the new
keyword:
In this example, apple
is a specific instance or object of our Fruit
class, much like a single building constructed from a shared blueprint.
To bestow behavior upon our class, we incorporate methods — these are functions that belong to a class. Let's add a straightforward printColor
method inside our Fruit
class:
The printColor
method here is a straightforward function that prints Red
to the console. Note that we didn't include the function
keyword - that's because JavaScript class syntax works this way.
Now, let's generate an instance of our class and invoke, or call
, the printColor
method we outlined previously:
We leveraged the printColor
method on our apple
instance, which resulted in Red
being printed on the console.
Great work! You've managed to understand what JavaScript classes are and have illustrated their significance in Object-Oriented Programming. We've journeyed through the process of creating a class, instantiating it, and invoking a class method. Now, let's solidify this newfound knowledge with some hands-on practice. So, put on your coding hat and get ready — remember, practice is integral to learning! Happy coding!
