Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

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 initializes name and age 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:

  1. Create a File:

    • Name it lesson21-classes.html.
  2. 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>
  3. Save the File:

    • Save it in your project folder.
  4. Preview the File:

    • Open it in your browser and check the console for output.

Experiment

Try modifying the class:

  1. 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
  2. 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.