AnyCompiler

Classes and Objects

A class is a blueprint for creating objects that bundle data (properties) together with the functions that operate on that data (methods). Every dog you create from a Dog class shares the same structure, but holds its own values.

class Dog {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  bark() {
    return `${this.name} says Woof!`;
  }
}

const myDog = new Dog("Rex", 3);
console.log(myDog.name);
console.log(myDog.bark());
Output
Rex
Rex says Woof!
  • constructor runs automatically when you create a new object with new — it's where you set up the object's starting data
  • this refers to the specific object a method is being called on — it's how a method reaches the object's own properties
  • this.name = name stores the value as a property, so every method on this object can access it later
  • new Dog("Rex", 3) creates an actual object (an "instance") of the Dog class

You could create as many dogs as you want from the same class — new Dog("Bella", 5), new Dog("Max", 1) — each one keeping its own name and age independently.

Next: promises and async/await — how JavaScript handles operations that take time.

Practice exercise

Add a honk() method to the Car class that returns `${this.make} says beep!`, then print the result of calling it on a new Car("Toyota").