Classes and Objects in JavaScript

Classes and Objects

Let's dive into a foundational concept in Object-Oriented Programming (OOP): Classes and Objects. If you have already explored OOP concepts in other programming languages or previous units, this might serve as a good reminder. If not, no worries — we'll start from the basics.

Classes and objects are the building blocks of OOP. A class acts as a blueprint for creating objects, which are instances of the class. Understanding these basics is essential before moving on to more advanced OOP topics like inheritance, polymorphism, and encapsulation.

Defining a Class

In JavaScript, a class is defined using the class keyword. A class serves as a blueprint to create objects. Here's a simple example:

JavaScript
// Defining a class named Person
class Person {
    // Constructor to initialize the object's data
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}

A class can have fields, methods, and constructors. In this snippet, we define a Person class with data members name and age.

What is an Object?

An object is an instance of a class. It represents a specific example of the class and holds the characteristics that define the class.

Objects have three main characteristics:

  • State: The data or attributes of the object. In the Person class, the name and age are the object's state.
  • Behavior: The methods and functions that the object can perform. In the Person class, the display method is mentioned here as an example of behavior, and it will be implemented later in this lesson.
  • Identity: A unique identifier distinguishes the object from others, even if they have the same state. This is handled by the memory address in JavaScript.

An object is thus a concrete instance of a class that includes state, behavior, and identity.

Using Constructors

Constructors initialize the newly created object's state. In the Person class, we use a constructor to set the name and age:

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

In JavaScript, this refers to the current instance of the class and is used to distinguish the class's fields from the parameters with the same names.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal