← Fundamentals
Fundamentals

TypeScript this and arrow functions

What decides this at a call, and how do you keep it when a method becomes a callback?

A callback’s receiver, reached object state and function identity must agree with the API using it.

Outcome

Predict this from how a function is called, keep it with an arrow function or bind when a method becomes a callback, and pass the same function object to code that compares handlers.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

this
For the ordinary unbound functions shown, the receiver supplied by the call. Arrows use lexical this, and bound ordinary calls retain a specified receiver.
Detached method
An ordinary unbound method extracted and called without a receiver; in strict code its this is undefined.
bind
Creates a distinct function that supplies its stored receiver for ordinary calls. Construction with new is a separate case.
Arrow function
A function with no own this; it uses the this of the code where it was written.
noImplicitThis
A TypeScript checking option that reports this with an implicit any type. It does not select JavaScript runtime strictness.

A function value and its receiver

For an ordinary unbound JavaScript function, the call expression supplies this. Reading a method property obtains a function value; the object from which it was read is a separate part of the later invocation. TypeScript checks this usage, while JavaScript’s call and strictness rules determine runtime behavior.

A bound function retains a receiver for ordinary calls, and an arrow uses this from its enclosing context. Callback registration also creates an identity requirement: cleanup may need the same function value that was registered. Plan receiver access and registration lifetime together.

01The call decides

Follow the receiver when a method is delegated

A visitor quote widget lists names, prices their selections and listens for host refresh events while open. These operations live in Greeter, Pricer and Clock objects, but the widget passes their callable values to other code. Check which object each resulting call actually uses before trusting its output.

Before passing the greeting method to a list callback, isolate the receiver question with counter.add. The program calls it through counter, then stores the same method value in add and calls it on its own. Predict what happens.

add is an ordinary method in an object literal. The source explicitly begins with a runtime strict-mode directive.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
"use strict";

const counter = {
  count: 0,
  add() {
    this.count += 1;

    return this.count;
  }
};

console.log(counter.add());

const add = counter.add;

console.log(add());
What does the program do?
TypeScript · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc --noEmit --strict main.ts && node main.ts

Use the TypeScript setup from the first reading and replace main.ts for each experiment. The first source has an explicit use strict directive. The command checks with tsc --noEmit, then Node runs the source; that checker invocation emits no JavaScript directive into the file Node reads.

02Fixing this

Try to call a prepared function with another receiver

The widget may retain a prepared callable rather than repeat its object lookup. This probe binds counter.add, then invokes that function normally and through call(other). It also calls the original method through other. Predict the three lines.

bound.call(other) tries to give the bound function a different this.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const counter = {
  count: 0,
  add() {
    this.count += 1;

    return this.count;
  }
};
const other = { count: 100, add: counter.add };

const bound = counter.add.bind(counter);

console.log(bound());
console.log(bound.call(other));
console.log(other.add());
What do the three lines print?
Loading A bound receiver survives a different call site…

03Arrow functions

Pass an instance-owned callback through a list

The widget also passes callbacks through containers that supply no object receiver. Clicker provides an onTap field initialized with an arrow. The program stores it twice and calls each entry on its own. Predict the count.

onTap is a class field initialised with an arrow function.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
class Clicker {
  clicks = 0;

  onTap = () => {
    this.clicks += 1;
  };
}

const clicker = new Clicker();
const handlers = [clicker.onTap, clicker.onTap];

for (const handler of handlers) handler();

console.log(`clicks ${clicker.clicks}`);
What does the program print?

04Repair the visitor quote widget

Greet, quote at the configured rate, then unsubscribe refresh ticks

The widget’s greeting list passes one callback per visitor. Its quote view multiplies every submitted amount by the configured rate, preserving list order. Its refresh counter subscribes on start and unsubscribes on stop, so reports count only tick events received while open; a later start resumes with the same counter state.

The supplied event bus is a deterministic host-event model, not a wall clock. A tick line means one refresh event. Start, stop, restart and report fixtures expose receiver loss and handler identity without needing timers or a browser.

Repair the visitor quote widget

A method passed as a callback, an ordinary function inside a method, then a handler that must be the same function twice.

  1. easy · F-THIS-V4-1 Greet through the greeter
  2. medium · F-THIS-V4-2 Price with this pricer’s rate
  3. hard · F-THIS-V4-3 Stop the clock’s own handler
In the frontend Keep the receiver-correct listener within one framework setup/cleanup lifetime. Optional

A quote widget can listen for browser resize events while mounted. The listener needs the widget as its receiver, and cleanup needs the exact listener value used for registration. The static examples keep that value inside one setup lifetime.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
"use client";

import { useEffect } from "react";

class Widget {
  label = "quote";

  refresh(event: Event) {
    console.log(this.label, event.type);
  }
}

export default function QuoteRefresh() {
  useEffect(() => {
    const widget = new Widget();
    const handler = widget.refresh.bind(widget);
    window.addEventListener("resize", handler);

    return () => window.removeEventListener("resize", handler);
  }, []);

  return <p>Quote widget resize listener</p>;
}

The bound handler supplies widget for ordinary refresh calls, while the cleanup closes over the same handler value. React may run Effect setup and cleanup more than once; each setup here owns its listener and matching cleanup. Browser EventTarget has its own duplicate-registration rules, unlike the lab Bus whose on appends handlers.

Sources: React: useEffect setup and cleanup,Svelte: onMount cleanup,DOM: event listeners.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.