欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

The Scope Chain

程序员文章站 2022-08-10 10:01:55
JavaScript is a lexically scoped language: the scope of variable can be thought of as the set of source code lines for which the variable is defined. ......

javascript is a lexically scoped language: the scope of variable can be thought of as the set of source code lines for which the variable is defined. global variables are defined throughout the program. local variables are defined throughout the function in which they are declared, and also within any functions nested within that function.

if we think of local variables as properties of some kind of implementation-defined object, then there is another way to think about variable scope. every chunk of javascript code (global code or functions) has a scope chain associated with it. this scope chain is a list or chain of objects that defines the variables that are "in scope" for that code. when javascript needs to look up the value of a variable x (a process called variable 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. if x is not a property of any of the objects in the scope chain, then x is not in scope for that code, and a referenceerror occurs.

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. in a non-nested function, the scope chain consists of two objects. the first is the object that defines the function's parameters and local variables, and the second is the global object. in a nested function, the scope chain has three or more objects. it is important to understand how this chain of objects is created. when a function is defined, it stores the scope chain then in effect. when that function is invoked, it creates a new object to store its local variables, and adds that new object to the stored scope chain to create a new, longer, chain that represents the scope for that function invocation. this becomes more interesting for nested functions because each time the outer function is called, the inner function is defined again. since the scope chain differs on each invocation of the outer function, the inner function will be identical on each invocation of the outer function, but the scope chain associated with that code will be different.