Lesson 1
Exploring JavaScript Classes: Blueprint to Object Creation
Topic Overview

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.

Understanding Classes in JavaScript

Think of a JavaScript class as a construction blueprint. By following the blueprint, we can create specifically structured objects, each filled with different values.

JavaScript
1class Fruit { 2}

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

Creating an instance of a class, essentially bringing an object to life from this blueprint, uses the new keyword:

JavaScript
1let apple = new Fruit();

In this example, apple is a specific instance or object of our Fruit class, much like a single building constructed from a shared blueprint.

Incorporating a Simple Function (Method) Inside a Class

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:

JavaScript
1class Fruit { 2 printColor() { 3 console.log('Red'); // This will print out 'Red' when called 4 } 5 6 printMessage(name) { 7 console.log(`Do you want a fruit, ${name}?`); 8 } 9}

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.

Using an Instance to Call a Method

Now, let's generate an instance of our class and invoke, or call, the printColor method we outlined previously:

JavaScript
1let apple = new Fruit(); 2apple.printColor(); // Outputs: Red 3apple.printMessage('John'); // Outputs: Do you want a fruit, John?

We leveraged the printColor method on our apple instance, which resulted in Red being printed on the console.

Lesson Summary and Practice

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!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.