HeadlinesBriefing favicon HeadlinesBriefing.com

JavaScript `this` Keyword Explained

DEV Community •
×

A developer's confusion over a function printing 'undefined' leads to a core lesson in JavaScript. The issue isn't the code itself, but the execution context. The keyword `this` isn't a fixed label; it's determined entirely by the 'call site'—specifically, what is to the left of the dot when the function is invoked.

When a method like `user.speak()` is called directly, `this` correctly refers to the `user` object. However, if that same function is assigned to a variable and called without an object prefix, `this` loses its context and becomes `undefined` in strict mode. To solve this, developers can use `.call()` for an immediate, specific context or `.bind()` to create a new function with a permanently locked `this` value.

Understanding this dynamic is critical for avoiding bugs in event handlers and callbacks where context often shifts unexpectedly.