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)
- Creates a new empty object
- Links its prototype to the class prototype
- Runs
constructorwiththisbound to that object - 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
javascript
Static Methods and Properties
Belong to the class, not each instance:
javascript
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 #
javascript
Constructor Functions (Legacy)
javascript
Mini Example: UUID Stub Generator
javascript
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?
Inheritance—extends and super.