jsverse
Core JavaScript / this

The this Keyword

this isn't fixed by where a function is written - it's decided by how the function is called.

Unlike most variables, `this` is not determined by lexical scope - it's determined at call time, by how a function is invoked. Called as `obj.method()`, `this` is `obj`. Called as a plain function, `this` is `undefined` in strict mode (or the global object otherwise). `call`, `apply`, and `bind` let you set `this` explicitly. Arrow functions are the one exception: they don't have their own `this` at all - they capture `this` lexically from whatever scope they were defined in.

Codeeditable — Run and Step both follow your edits
Loading...
Console
Output will appear here
Visualization
Result
Press Step to watch each line's result appear here
Why?

greet is called as user.greet(), so this is user. greetLater is an arrow function - it has no this of its own, so it uses this from the surrounding (module/global) scope, where name doesn't exist.