All academies

Constructors

How constructors initialize objects and allocate memory.

12 minLevel 4 of 20

Role of the constructor

The constructor runs when you new a class. It initializes state and is the natural place to receive dependencies — Nest's DI injects constructor parameters automatically.

Constructor init
class Session {
  readonly startedAt: Date;
  constructor(public userId: string) {
    this.startedAt = new Date();
    console.log("Session created for", userId);
  }
}
const s = new Session("u-42");
console.log(s.userId, s.startedAt instanceof Date);

Constructor chaining with super

Subclasses must call super(...) before using this. That chains construction up the inheritance tree — important when you extend base services or abstract classes.

super()
class Animal {
  constructor(public name: string) { console.log("Animal", name); }
}
class Dog extends Animal {
  constructor(name: string, public breed: string) {
    super(name);
    console.log("Dog", breed);
  }
}
new Dog("Rex", "Lab");

DI-friendly constructors

Keep constructors for wiring, not heavy business logic. Nest resolves the graph by reading constructor types (and tokens).

Injection-shaped ctor
class Mailer { send(msg: string) { console.log(msg); } }
class NotifyService {
  constructor(private readonly mailer: Mailer) {}
  welcome(email: string) { this.mailer.send("Welcome " + email); }
}
new NotifyService(new Mailer()).welcome("ada@ex.com");

Check your understanding

5 questions

Question 1 of 5

Score: 0

Multiple choice

When does a constructor run?