Sub topic 4
Methods and the `this` keyword
Prerequisites and the working model
Assume you know basic TypeScript types, functions, objects, and the JavaScript this keyword. A method is a function declared inside a class. It usually reads or changes the object’s fields.
Inside a method, this refers to the instance that called the method. TypeScript checks that fields and methods accessed through this exist and have the declared types.
class Counter {
private value = 0;
increment(amount: number): void {
this.value += amount;
}
current(): number {
return this.value;
}
}
const counter = new Counter();
counter.increment(3);
console.log(counter.current()); // 3When counter.increment(3) runs, this inside increment refers to counter. The method can therefore update counter.value.
Method parameters and return types
Annotate method parameters and return values just as you would for ordinary functions. A void return type means the method does not return a useful value.
Methods can return objects, unions, or other class instances:
class User {
constructor(
public readonly name: string,
private active: boolean
) {}
deactivate(): void {
this.active = false;
}
status(): "active" | "inactive" {
return this.active ? "active" : "inactive";
}
}
const user = new User("Mina", true);
user.deactivate();
console.log(user.status()); // inactiveThe private field can be changed by class methods, but callers must use the public methods.
When `this` is lost
The value of this comes from how a function is called, not where it was declared. If you store a method and call it as a plain function, it may no longer refer to the instance.
class Greeter {
constructor(private message: string) {}
greet(): string {
return this.message;
}
}
const greeter = new Greeter("Hello");
const sayHello = greeter.greet;
// sayHello(); // Error or runtime failure: this is not the Greeter instanceUse bind when passing a normal method as a callback:
const safeSayHello = greeter.greet.bind(greeter);
console.log(safeSayHello()); // HelloAnother option is an arrow-function field. Arrow functions capture this from the surrounding instance:
class Timer {
seconds = 0;
tick = (): void => {
this.seconds++;
};
}
const timer = new Timer();
const callback = timer.tick;
callback();
console.log(timer.seconds); // 1Arrow-function fields are convenient for callbacks, but each instance creates its own function. Use ordinary methods when you do not need a permanently bound callback.
Exercise
Why does const callback = timer.tick; callback(); work in the Timer example, while extracting greeter.greet can fail?
Show answer
tick is an arrow-function field, so it captures the instance's this. greet is an ordinary method, so extracting it removes the receiver that supplied this.