All academies

Methods

Instance methods, this binding, and message-passing between objects.

14 minLevel 6 of 20

Methods and this

Methods are functions attached to instances. Inside a method, this refers to the receiver object — unless you detach the method and lose the binding.

this binding
class Greeter {
  constructor(public name: string) {}
  hi() { return "Hi " + this.name; }
}
const g = new Greeter("Ada");
console.log(g.hi());
const detached = g.hi;
try { console.log(detached()); } catch (e) {
  console.log("detached failed:", (e as Error).message);
}

Command vs query

A useful design habit: commands change state; queries return info without side effects. Nest services stay clearer when you separate them.

Command / query
class Counter {
  private n = 0;
  inc() { this.n++; }          // command
  value() { return this.n; }   // query
}
const c = new Counter();
c.inc(); c.inc();
console.log(c.value());

Delegation between objects

Methods often delegate to collaborators — the heart of DI. The method's job is orchestration, not owning every detail.

Delegation
class Tax {
  calc(amount: number) { return amount * 0.1; }
}
class CheckoutService {
  constructor(private tax: Tax) {}
  total(amount: number) {
    return amount + this.tax.calc(amount);
  }
}
console.log(new CheckoutService(new Tax()).total(100));

Check your understanding

5 questions

Question 1 of 5

Score: 0

Multiple choice

In an instance method, this usually refers to: