Skip to the workspace
Pebellslearn by building
Using (this) keyword  ›  Lesson

this Used Alone, and in Event Handlers

using it alone 15 min

javascript / this Used Alone, and in Event Handlers

Explore each scene at your own pace.

01 · this Used Alone, and in Event Handlers

this Used Alone, and in Event Handlers

this Used Alone, and in Event Handlers

Top-level this depends on the execution context. In an ordinary DOM event listener, this is the element receiving that listener call; an arrow does not receive that event binding.

Inspect the host and call form instead of memorizing that this always means window.

See the mechanism

Walk through the modelthis Used Alone, and in Event HandlersAuthored snapshots of the example; use Run below to test the code.
Stateordinary function registered on button
The browser will supply this when dispatching this callback.
1 of 3

Follow one example

html

This ordinary listener is invoked with the button as this, matching event.currentTarget during the callback. An arrow would resolve this lexically instead. In a browser classic script, top-level this is usually the global object; in an ES module it is undefined. A console, worker or wrapper may provide another context, so test the intended environment.

Predict, change and check

Predict: If you change the listener to an arrow, can you still rely on this being the button?

Test your explanation: Use event.currentTarget explicitly so the code does not depend on the callback’s this binding. Verify the updated version by clicking the button.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Top-level and event contexts differ

Top-level this differs across classic scripts, ESM and Node module contexts. Do not use one page-console observation as a rule for every JavaScript host. In a DOM listener registered with an ordinary function, this normally corresponds to the listener's current element; an arrow does not get that same dynamic binding.

Prefer event.currentTarget when teaching which element owns the current listener, and capture what you need synchronously before an asynchronous continuation. An event's origin can be a child element, so event.target is not always the button you registered on. Test a click on a nested span as well as on the button background.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.