All academies

Objects

Objects as bundles of state and behavior — identity, state, and messages.

12 minLevel 2 of 20

What is an object?

An object has three traits:

  • Identity — distinct from other objects even with the same data
  • State — current property values
  • Behavior — methods you can call (messages)

In TypeScript, object literals and class instances are both objects — Nest providers are class instances with identity managed by the container.

Identity vs equality
const a = { id: 1, name: "Ada" };
const b = { id: 1, name: "Ada" };
console.log("same contents?", a.id === b.id && a.name === b.name);
console.log("same identity?", a === b); // false — two objects

Messages and collaboration

OOP programs work by objects sending messages (calling methods) to each other. A controller does not reach into a service's private fields — it asks the service to do work.

That message-passing style is exactly how Nest request flow feels: Controller → Service → Repository.

Message passing
class Inventory {
  private stock = 10;
  reserve(qty: number) {
    if (qty > this.stock) throw new Error("out of stock");
    this.stock -= qty;
    return this.stock;
  }
}
class Checkout {
  constructor(private inventory: Inventory) {}
  buy(qty: number) {
    const left = this.inventory.reserve(qty);
    return `Reserved ${qty}, left ${left}`;
  }
}
console.log(new Checkout(new Inventory()).buy(3));

Objects in memory

Each new allocates a distinct heap object. Variables hold references. Assigning const b = a copies the reference, not the object — mutating through b changes what a sees.

Shared reference
const order = { total: 20 };
const alias = order;
alias.total = 50;
console.log(order.total); // 50 — same object

Check your understanding

5 questions

Question 1 of 5

Score: 0

Multiple choice

Object identity means: