Welcome to the World of Classes in JavaScript!
In this tutorial, we're going to create a Car
class that will help us model a car with properties like make
, model
, and year
. Are you excited?
Step 1: Create a Car
Class
Open your index.js
file and add the following code:
class Car { // We'll add properties and methods here}
What's a Class?
In JavaScript, a class is a blueprint for creating objects. Think of it like a recipe for making a cake. You can use the recipe (class) to create multiple cakes (objects) with different flavors and toppings.
Step 2: Add Properties to the Car
Class
Let's add the make
, model
, and year
properties to our Car
class:
class Car { constructor(make, model, year) { this.make = make; this.model = model; this.year = year; }}
What's a Constructor?
A constructor is a special method in a class that's called when an object is created from the class. It's like a setup method that initializes the object with the given properties.
Step 3: Create a Car
Object
Let's create a Car
object using our Car
class:
const myCar = new Car("Toyota", "Corolla", 2015)
What's new
?
The new
keyword is used to create a new object from a class. It's like using a mold to create a new cake from our recipe (class).
Step 4: Log the Car
Object
Let's log our myCar
object to the console:
console.log(myCar)
Run the Code!
Click the "Run" button to execute the code. You should see the following output in the console:
Car { make: "Toyota", model: "Corolla", year: 2015 }
Step 5: Add a Method to the Car
Class
Let's add a startEngine
method to our Car
class:
class Car { constructor(make, model, year) { this.make = make this.model = model this.year = year }
startEngine() { console.log("Vroom! The engine is started.") }}
What's a Method?
A method is a function that's part of a class. It's like a recipe instruction that can be executed on an object.
Step 6: Call the startEngine
Method
Let's call the startEngine
method on our myCar
object:
myCar.startEngine();
Run the Code Again!
Click the "Run" button to execute the code. You should see the following output in the console:
Vroom! The engine is started.
Congratulations!
You've just created a Car
class with properties and a method! You can now create multiple Car
objects with different properties and call the startEngine
method on each of them.
What's Next?
In the next tutorial, we'll explore inheritance in JavaScript. Are you ready to take your coding skills to the next level?
Happy coding!
Tests