Managing Scope
Managing Scope
When JavaScript code is being executed, an execution context is created. The execution
context (also sometimes called the scope) defines the environment in which code is to
be executed. A global execution context is created upon page load, and additional
execution contexts are created as functions are executed, ultimately creating an execution
context stack where the topmost context is the active one.
Each execution context has a scope chain associated with it, which is used for identifier
resolution. The scope chain contains one or more variable objects that define in-scope
identifiers for the execution context. The global execution context has only one variable object in its scope chain, and this object defines all of the global variables and functions
available in JavaScript. When a function is created (but not executed), its internal
[[Scope]] property is assigned to contain the scope chain of the execution context in
which it was created (internal properties cannot be accessed through JavaScript, so you
cannot access this property directly). Later, when execution flows into a function, an
activation object is created and initialized with values for this, arguments, named
arguments, and any variables local to the function. The activation object appears first
in the execution context’s scope chain and is followed by the objects contained in the
function’s [[Scope]] property.
During code execution, identifiers such as variable and function names are resolved by
searching the scope chain of the execution context. Identifier resolution begins at the
front of the scope chain and proceeds toward the back. Consider the following code:
function add(num1, num2){
return num1 + num2;
}
var result = add(5, 10);
When this code is executed, the add function has a [[Scope]] property that contains
only the global variable object. As execution flows into the add function, a new execution
context is created, and an activation object containing this, arguments, num1, and
num2 is placed into the scope chain. Figure 7-1 illustrates the behind-the-scenes object
relationships that occur while the add function is being executed.
沒有留言:
張貼留言