JavaScript Classes, Objects, and Constructors

Object-Oriented Programming (OOP) is a way to organize your code by grouping related data and actions into reusable pieces called objects. In JavaScript, this became easier with the class keyword introduced in ES6. It lets you create blueprints for objects, like templates, so you can build things like users, cars, or games in a clear and structured way.



What is OOP?

OOP is a way to organize code into reusable and modular pieces. These pieces are called objects. Objects represent real-world things and can have properties (data) and methods (functions).

  • Class – A blueprint for creating objects.
  • Object – An instance of a class.
  • Constructor – A special method used to initialize objects.
  • Inheritance – One class can inherit properties and methods from another.
  • Encapsulation – Keeping data safe and controlled through access restrictions.
  • Polymorphism – Different objects can share the same method name but perform different actions (method overriding).

Class

A class is a blueprint or template for creating objects. It defines the properties (data) and methods (functions) that the objects created from the class will have.

Here’s a simple example:

javascript
// Creating a class named Car that models a car with make and model properties
class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }

  displayInfo() {
    console.log(`Car: ${this.make} ${this.model}`);
  }
}

Let’s break it down:

  • class Car defines the structure and behavior of car objects.
  • The constructor method sets up initial values for make and model.
  • displayInfo() is a method that prints car details to the console.

Object

An object is a specific instance of a class. It contains real values for the properties defined in the class and can use its methods to perform actions.

Here's how you create an object from the Car class:

javascript
class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }

  displayInfo() {
    console.log(`Car: ${this.make} ${this.model}`);
  }
}
 
// Creating an object named myCar from the Car class
const myCar = new Car("Ford", "Mustang");
myCar.displayInfo(); // Output: Car: Ford Mustang

Here’s what’s happening step-by-step:

  • new Car("Ford", "Mustang") creates a new instance (object) of the Car class.
  • The object myCar stores the values make = "Ford" and model = "Mustang" for that specific car.
  • We call the displayInfo() method on myCar to show the car’s details in the console.

Constructor and this keyword

The constructor is a special method inside a class. It runs automatically when a new object is created. You use it to set up initial properties for that object.

The keyword this refers to the current object being created. It helps assign values to that object’s properties.

Here’s a simple example:

javascript
class Car {
  constructor(make, model) {
    this.make = make;    // Set the make property for this object
    this.model = model;  // Set the model property for this object
  }
}

Here’s how it works:

  • The constructor method runs automatically when you create a new object using the class.
  • this.make assigns the passed-in make value to the object being created.
  • this.model does the same for the model property.
  • The keyword this refers to the current object inside the class.

Example 1: Class, Object, Constructor, and this

This example shows how to define a class using the class keyword, create an object from that class, and use the constructor and this keyword to set up and access properties.

javascript
//🚘 This is a class named Car
class Car {
  // This is the constructor method
  constructor(make, model) {
    // 'this' refers to the current object being created
    this.make = make;   // Set the 'make' property
    this.model = model; // Set the 'model' property
  }

  // A method to display car information
  displayInfo() {
    console.log(`Car: ${this.make} ${this.model}`);
  }
}

// This is an object created from the Car class
const myCar = new Car("Nissan", "GT-R");

// Calling a method on the object
myCar.displayInfo(); // Output: Car: Nissan GT-R

How It Works:

  • class Car defines a template for creating car objects.
  • The constructor method runs when a new object is created and sets up the object's initial data.
  • this refers to the current object, allowing access to its properties and methods.
  • myCar is an object created using the new keyword with specific values.
  • The displayInfo() method prints the object's information to the console.

Output

Car: Nissan GT-R

🧠 This example helps you understand how classes are used to create objects, and how constructors and this make it easy to work with object properties.


Example 2: Creating Multiple Objects from the Same Class

In this example, we use the same class to create different objects, each with its own data. This shows how classes help reuse structure and behavior across multiple instances.

javascript
// Class definition
class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }

  displayInfo() {
    console.log(`Car: ${this.make} ${this.model}`);
  }
}

// Creating multiple objects using the same class
const car1 = new Car("Ford", "Mustang");
const car2 = new Car("Nissan", "GT-R");

// Calling methods on each object
car1.displayInfo(); // Output: Car: Ford Mustang
car2.displayInfo(); // Output: Car: Nissan GT-R

How It Works:

  • Car is a class that defines how a car should be structured.
  • car1 and car2 are two separate objects created from the Car class.
  • Each object holds its own make and model values.
  • The displayInfo() method is shared, but it works based on each object’s specific data.

Output

Car: Ford Mustang
Car: Ford Mustang

🧠 This example shows how powerful classes are β€” you can create many unique objects using the same class blueprint.


Example 3: Class with Multiple Methods

This example shows how a class can have more than one method. Methods help objects perform actions like showing info, updating data, or checking conditions.

javascript
// Class with multiple methods
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  // Method 1: Greet the user
  greet() {
    console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);
  }

  // Method 2: Update the person's age
  updateAge(newAge) {
    this.age = newAge;
    console.log(`${this.name}'s age is now ${this.age}.`);
  }

  // Method 3: Check if the person is an adult
  isAdult() {
    return this.age >= 18;
  }
}

// Creating an object
const person1 = new Person("Emma", 17);

// Calling methods
person1.greet();            // Hi, I'm Emma and I'm 17 years old.
person1.updateAge(20);      // Emma's age is now 20.
console.log(person1.isAdult()); // true

How It Works:

  • greet() displays the person's name and age.
  • updateAge() changes the age property to a new value.
  • isAdult() returns true if the person is 18 or older.
  • person1 is an object that can use all of these methods.

Output

Hi, I'm Emma and I'm 17 years old.
Emma's age is now 20.
true

🧠 This example shows how you can group multiple related behaviors inside a class, making your code clean and organized.


Frequently Asked Questions

What is a class in JavaScript?

A class in JavaScript is a blueprint for creating objects. It allows you to define properties and methods that each object created from the class will have.


How do you create an object from a class?

You can create an object from a class using the new keyword. For example: const myCar = new Car('Toyota', 'Corolla');


What is the constructor in a JavaScript class?

The constructor is a special method inside a class that runs automatically when a new object is created. It’s used to initialize the object's properties.


What does the this keyword mean in a class?

In a class, this refers to the current object being created or used. It is used to access the object's properties and methods.


Can one class create multiple objects?

Yes, a single class can be used to create multiple objects, each with its own set of data but sharing the same structure and behavior defined by the class.



What's Next?

Up next, we’ll explore static methods and properties in JavaScript. These are special features you can use with classes, and they work a little differently from regular methods.