HTML and CSS Reference
In-Depth Information
This example shows a few interesting aspects. The
i
variable is declared even
before the
var
statement inside the
for
loop. Notice how accessing some arbi-
trary variable will not work, and throws a
ReferenceError
(or
TypeError
in
Internet Explorer). Furthermore, the
i
variable is still accessible, and has a value,
after the
for
loop. A common error in methods that use more than one loop is to
redeclare the
i
variable in every loop.
In addition to global scope and function scope, the
with
statement can alter
the scope chain for its block, but its usage is usually discouraged and it is effectively
deprecated in ECMAScript 5 strict mode. The next version of ECMAScript, cur-
rently a work-in-progress under the name of “Harmony”, is slated to introduce block
scope with the
let
statement.
let
has been available as a proprietary extension to
Mozilla's JavaScript
™
since version 1.7, first released with Firefox 2.0.
5.3.1 Execution Contexts
The ECMAScript specification describes all JavaScript code to operate in an
ex-
ecution context.
Execution contexts are not accessible entities in JavaScript, but
understanding them is vital to fully understand how functions and closures work.
From the specification:
“Whenever control is transferred to ECMAScript executable code, control is
entering an execution context. Active execution contexts logically form a stack. The
top execution context on this stack is the running execution context.”
5.3.2 The Variable Object
An execution context has a variable object. Any variables and functions defined in-
side the function are added as properties on this object. The algorithm that describes
this process explain all of the examples in the previous section.
For any formal parameters, add corresponding properties on the variable
object and let their values be the values passed as arguments to the function.
•
•
For any function declarations, add corresponding properties on the variable
object whose values are the functions. If a function declaration uses the same
identifier as one of the formal parameters, the property is overwritten.
•
For any variable declarations, add corresponding properties on the variable
object and initialize the properties to
undefined
, regardless of how the
variables are initialized in source code. If a variable uses the same identifier
as an already defined property (i.e., a parameter or function), do not
overwrite it.