Classes & Constructors

JavaScript classes provide a clear, concise syntax to create objects and manage inheritance. They act as blueprints for objects, defining properties and behaviors.

What is a Class?

A class is a template for creating objects. It encapsulates data (properties) and functions (methods) that operate on that data.

Constructor Method

The constructor is a special method inside a class. It runs automatically when you create a new instance, setting initial property values.

Illustration of classes_constructors
Illustration of classes_constructors

💡 Constructor Basics

Every class can have only one constructor method. It is called when you create an object with new.

Creating a Class with a Constructor

Here’s the simplest way to create a class with a constructor that initializes properties:

📌 Deep Dive: Defining a Class and Constructor

JAVASCRIPT
class Car {
  constructor(make, model) {
    this.make = make;   // Property 'make' initialized
    this.model = model; // Property 'model' initialized
  }
}

Instantiating Objects

Use the new keyword to create an instance of the class and pass arguments to the constructor:

📌 Deep Dive: Creating an Instance

JAVASCRIPT
const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.make);  // Output: Toyota
console.log(myCar.model); // Output: Corolla
Output
Toyota
Corolla

Key Points About Classes & Constructors

  • Classes are syntactic sugar over JavaScript's prototype-based inheritance.
  • The constructor method initializes new objects.
  • If no constructor is defined, a default empty constructor is used.
  • Use this to assign properties inside the constructor.
Class vs Constructor Function
Class SyntaxConstructor Function
Cleaner, easier to readTraditional, verbose
Supports extends for inheritanceUses prototypes explicitly
Must use constructor methodFunction itself acts as constructor

⚠️ Important

Calling a class without new will throw an error. Always use new when instantiating.

Adding Methods to a Class

Methods can be declared inside the class but outside the constructor. They become part of the object's prototype.

📌 Deep Dive: Adding Methods

JAVASCRIPT
class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }
  getDescription() {
    return `${this.make} ${this.model}`;
  }
}

const myCar = new Car('Honda', 'Civic');
console.log(myCar.getDescription()); // Honda Civic
Output
Honda Civic

💡 Summary

Classes organize code by combining properties and methods. Constructors set initial values, and methods define behavior.