this in event listeners
A function listener gets the element it is attached to as this. An arrow listener keeps the outside this; use event.currentTarget there instead (Phase 9).
this is a hidden extra input to every regular function, and its value is decided by how the function is called, not where it was written; arrow functions are the exception, because they have no this of their own and use the one around them.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Predict the four lines this prints, then run it: "use strict"; const cat = { name: "Milo", speak() { return this?.name ?? "nobody"; } }; const dog = { name: "Rex", speak: cat.speak }; const s = cat.speak; console.log(cat.speak()); console.log(dog.speak()); console.log(s()); console.log((0, cat.speak)());
A stopwatch object has seconds: 0 and a start() method that should add 1 to this.seconds every second with setInterval. Write start() so this works, and say why a function callback would fail.
Write an object greeter with a names array and a greetAll() method that returns an array of "Hello, <name> from <greeter.place>" strings, reading place through this inside the map callback.
Explain it without notes
How is the value of this decided inside a regular function?
Why does passing obj.method to setTimeout or addEventListener lose this, and how do you fix it?
How do arrow functions handle this, and when is that a problem?
What is this at the top level of a classic script, of a module, and inside a plain function call in strict and sloppy mode?
Preview
Console
Nothing logged yet.Expected console output
function listener, this is <button#save>
arrow listener, this is window? true