Constructors in JavaScript

Introduction

A constructor runs when you create an instance with new. In classes, the constructor method initializes this. In older code, constructor functions did the same job. This chapter covers initialization rules, returning from constructors, and static methods that belong to the class itself.

Prerequisites

Class constructor

javascript
// constructor sets instance state
class User {
  constructor(name, email) {
    this.name = name;
    this.email = email;
    this.createdAt = new Date().toISOString();
  }
}
 
const user = new User("Ada", "ada@example.com");
console.log(user.name, user.createdAt);

What new Does (Simplified)

  1. Creates a new empty object
  2. Links its prototype to the class prototype
  3. Runs constructor with this bound to that object
  4. Returns the object (unless constructor returns a different object)
javascript
// Manual mental model (do not use in production)
function Person(name) {
  this.name = name;
}
 
const p = new Person("Lin");
console.log(p.name);

Parameter Validation in Constructor

Static Methods and Properties

Belong to the class, not each instance:

javascript
// Static counter
class RequestId {
  static #seq = 0;
 
  static next() {
    RequestId.#seq += 1;
    return RequestId.#seq;
  }
}
 
console.log(RequestId.next());
console.log(RequestId.next());

Private Fields with #

Constructor Functions (Legacy)

Mini Example: UUID Stub Generator

FAQ

Must constructor be named constructor?

In a class, yes—only one constructor method (or none for empty default).

Can constructor be async?

async constructor is invalid—use a static async create() factory instead.

Static vs instance method?

Static: Math.max, factories, counters. Instance: behavior on one object's data.

What comes next?

Inheritanceextends and super.