Logo

Developer learning path

JavaScript

Classes in JavaScript

Classes

3

#description

In JavaScript, classes provide a way to create objects with a blueprint that defines their properties and behavior.

To create a class, you can use the class keyword followed by the name of the class. Inside the class, you can define properties and methods using the same syntax as object literals. Properties are variables that hold values, while methods are functions that perform actions.

Here's an example of a class for a Person:

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

  sayHello() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}
                  

In this example, Person is the name of the class. The constructor method is a special method that gets called when an instance of the class is created. It takes two arguments: name and age.

The sayHello method is a regular method that logs a message to the console with the person's name and age.

To create an instance of the Person class, you can use the new keyword followed by the class name:

                    
const john = new Person('John', 25);
                  

This creates a new Person object with the name "John" and age 25.

You can then call the sayHello method on the object:

                    
john.sayHello(); // Hello, my name is John and I am 25 years old.
                  

Classes also support inheritance, which allows you to create a new class based on an existing class. Inheritance is accomplished through the extends keyword.

Here's an example of a Student class that inherits from Person:

                    
class Student extends Person {
  constructor(name, age, grade) {
    super(name, age);
    this.grade = grade;
  }

  sayHello() {
    console.log(`Hello, my name is ${this.name}, I'm a student and I'm in grade ${this.grade}.`);
  }
}
                  

In this example, Student is a new class that extends the Person class. It has a constructor method that takes three arguments: name, age, and grade.

The super keyword is used to call the parent class constructor and pass in the name and age arguments.

The sayHello method is also overridden to include the student's grade. When calling the sayHello method on a Student object, the overridden method will be called instead of the one defined in the parent Person class.

March 25, 2023

If you don't quite understand a paragraph in the lecture, just click on it and you can ask questions about it.

If you don't understand the whole question, click on the buttons below to get a new version of the explanation, practical examples, or to critique the question itself.