Variable Scope Revisited
When we first discussed the notion of variable scope, I based the definition solely on the lexical structure of JavaScript code: global variables have global scope and variables declared in functions have local scope. If one function definition is nested within another, variables declared within that nested function have a nested local scope. Now that we know that global variables are properties of a global object and that local variables are properties of a special call object, we can return to the notion of variable scope and reconceptualize it. This new description of scope offers a useful way to think about variables in many contexts; it provides a powerful new understanding of how JavaScript works.
Every
JavaScript execution context has a scope chain
associated with it. This scope chain is a list or chain of objects.
When JavaScript code needs to look up the value of a variable
x (a process called variable name resolution), it starts by looking at the first object
in the chain. If that object has a property named
x, the value of that property is used. If
the first object does not have a property named
x, JavaScript continues the search with
the next object in the chain. If the second object does not have a
property named x, the search moves on to
the next object, and so on.
In top-level JavaScript code (i.e., code not contained within any function definitions), the scope chain consists of a single object, the global object. All variables are looked ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access