Member-only story
Mastering the ‘this’ keyword in JavaScript is considered somewhat of a rite of passage for developers. The flexible ways it binds to values often trip up both beginners and experienced programmers alike.
Luckily, while complex, ‘this’ follows a set of predictable binding rules. Understanding these gives us the power to intentionally control context and write cleaner component logic.
Let’s demystify how ‘this’ works step-by-step!
Dynamic Binding
The key thing that makes ‘this’ confusing is its binding is dynamic instead of lexical. Its value depends on how the containing function is called, not where the function is defined.
Consider this example:
function logThis() {
console.log(this);
}
logThis(); // logs the global object (window/global)
Even though logThis is defined on its own here, when we call it by itself, the this value points to a default global object instead. The binding happens dynamically on invocation.