Lesson 21 - JavaScript Class Basics
What are Classes in JavaScript?
- A class is a blueprint for creating objects.
- It allows you to define properties and methods that every object created from it will have.
- Encapsulation: Bundles data and methods inside a single unit.
Before ES6, JavaScript used constructor functions to create objects, but classes made it more structured.
Explanation
- Classes use the
class
keyword. - A
constructor
method initializes object properties. - We use
new
to create an object from a class.
Example 1: Creating a Simple Class
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
const john = new Person("John Doe", 30);
console.log(john.greet());
// Output: Hello, my name is John Doe and I am 30 years old.
How it works?
- The
constructor
initializesname
andage
properties. - The
greet
method returns a greeting. new Person("John Doe", 30)
creates an object with values.
Example 2: Adding Methods to a Class
class Car {
constructor(brand, model, year) {
this.brand = brand;
this.model = model;
this.year = year;
}
carInfo() {
return `${this.brand} ${this.model} (${this.year})`;
}
}
const myCar = new Car("Toyota", "Camry", 2022);
console.log(myCar.carInfo());
// Output: Toyota Camry (2022)
Why use a class?
- It organizes data and behaviors together.
- Makes code cleaner and easier to maintain.
Try Your Hand
Follow these steps to create your own class!
Steps:
-
Create a File:
- Name it
lesson21-classes.html
.
- Name it
-
Write the Code:
- Copy the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lesson 21 - JavaScript Classes</title> </head> <body> <script> class Animal { constructor(name, sound) { this.name = name; this.sound = sound; } makeSound() { return `${this.name} says ${this.sound}`; } } const dog = new Animal("Dog", "Woof!"); console.log(dog.makeSound()); // Output: Dog says Woof! </script> </body> </html>
-
Save the File:
- Save it in your project folder.
-
Preview the File:
- Open it in your browser and check the console for output.
Experiment
Try modifying the class:
-
Add a method that doubles the age of a person:
class Human { constructor(name, age) { this.name = name; this.age = age; } doubleAge() { return this.age * 2; } } const user = new Human("Alice", 25); console.log(user.doubleAge()); // Output: 50
-
Modify the
Animal
class to accept more details:class Animal { constructor(name, sound, type) { this.name = name; this.sound = sound; this.type = type; } details() { return `${this.name} is a ${this.type} and makes a "${this.sound}" sound.`; } } const cat = new Animal("Cat", "Meow!", "mammal"); console.log(cat.details());
Key Takeaways
- Classes create reusable blueprints for objects.
- Use
constructor()
to initialize properties. - Define methods inside the class for functionality.
- Use
new
to create an instance of a class.