HTML and CSS Reference
In-Depth Information
The effects of this algorithm is known as
hoisting
of functions and variable
declarations. Note that although functions are hoisted in their entirety, variables
only have their declaration hoisted. Initialization happens where defined in source
code. This means that the code in Listing 5.12 is interpreted as Listing 5.13.
Listing 5.13
Function scope after hoisting
"test scope": function () {
function sum() {
var i;
var l;
assertUndefined(i);
/* ... */
}
sum(1, 2, 3, 4, 5);
}
This explains why accessing the
i
variable before the
var
statement yields
undefined
whereas accessing some arbitrary variable results in a reference error.
The reference error is further explained by how the scope chain works.
5.3.3 The Activation Object
The variable object does not explain why the
arguments
object is available inside
the function. This object is a property of another object associated with execution
contexts, the
activation object.
Note that both the activation object and the variable
object are purely a specification mechanism, and cannot be reached by JavaScript
code. For the purposes of identifier resolution, i.e., variable and function resolution,
the activation object and the variable object are the same object. Because properties
of the variable object are available as local variables inside an execution context, and
because the variable object and the activation object is the same object, function
bodies can reach the
arguments
object as if it was a local variable.
5.3.4 The Global Object
Before running any code, the JavaScript engine creates a global object whose initial
properties are the built-ins defined by ECMAScript, such as
Object
,
String
,
Array
and others, in addition to host defined properties. Browser implementations
of JavaScript provide a property of the global object that is itself the global object,
namely
window
.