Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 7.1 — The this Keyword
JavaScript · Example 1 of 4

The call site decides this

Both objects hold the very same function. Only the call changes this. Remove "use strict" and the third line changes, because sloppy mode gives window instead.

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.

01

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)());

02

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.

03

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

01

How is the value of this decided inside a regular function?

02

Why does passing obj.method to setTimeout or addEventListener lose this, and how do you fix it?

03

How do arrow functions handle this, and when is that a problem?

04

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?

The call site decides this

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

I am Asha
I am Ravi
this is undefined
Same function? true