D DevBrainBox

JavaScript Objects Classes

JS

What is a class?

A class in JavaScript is a blueprint for creating objects. It lets you create multiple similar objects (instances) without repeating the code.

Classes were introduced in ES6 (2015). They make working with object-oriented patterns easier and more readable.

Defining a class

Use the class keyword:

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

  greet() {
    console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);
  }
}
  • constructor() is a special method called automatically when you create a new object.
  • this refers to the new object being created.
  • greet is a method that can be called on any instance.

Creating an instance (object) from a class

const alice = new Person("Alice", 25);
const bob = new Person("Bob", 30);

alice.greet(); // Hi, I'm Alice and I'm 25 years old.
bob.greet();   // Hi, I'm Bob and I'm 30 years old.

On this page