Course contentsShow
← JavaScript
Lesson 539 of 2,72314. The 'this' KeywordFree lesson

Lexical Variables vs 'this'

Contrasting how regular variables use lexical scope while 'this' ignores lexical scope entirely.

Lexical Variables vs 'this'

What You'll Learn

You'll understand the fundamental difference between how regular variables follow lexical (static) scope rules while this completely ignores lexical scope and uses dynamic binding instead.

The Core Difference

When you use a regular variable inside a function, JavaScript looks it up using lexical scope—it searches outward through the nested scopes based on where the function was written in your code. This lookup is predictable and determined at parse time.

But this doesn't work that way at all. It ignores the lexical structure completely and instead depends on how the function is called at runtime. Two invocations of the same function can have completely different this values, even though the lexical scope remains identical.

An Analogy

Think of lexical variables like your home address—it's fixed based on where your house was built and never changes. The this keyword is like "the person standing in front of you right now"—it depends entirely on the current situation, not on any permanent location.

Why This Matters

This distinction explains why closures capture variables reliably (they use lexical scope), but this can seem unpredictable (it uses call-time binding). When you nest functions, inner functions can access outer variables through the scope chain, but they can't "inherit" this the same way—each function call gets its own this based on how it's invoked.

Understanding that these are two completely separate mechanisms helps you predict when this will "lose" its value (when passed as a callback) versus when regular variables stay captured perfectly (closures).

Key Takeaway: Regular variables use lexical scope (where you write the code), while this uses dynamic binding (how you call the function)—they're fundamentally different lookup mechanisms.