Reputation: 35
I read these lines in "JavaScript The Definite Guide" and I am not able to understand why scope chain of inner function will be different each time function is invoked
"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 subtly different each time it is defined—the code of the inner
function will be identical on each invocation of the outer function, but the scope chain
associated with that code will be different."
Upvotes: 0
Views: 263
Reputation: 943217
Every time you call a function, you create a new scope for that invocation of the function.
Any variables defined (with var
, function declarations, or as a named parameter) in that function are scoped to that function.
function foo (bar) { };
foo(1);
foo(2);
In the above, two scopes are created. In one of them, bar
is 1
in the other bar
is 2.
If a function is defined in another function, then it has access to the scope it was created in.
function foo (bar) { return function () { console.log(bar); } };
var foo1 = foo(1);
var foo2 = foo(2);
The function assigned to foo1
has access to the scope where bar
is 1
.
The function assigned to foo2
has access to the scope where bar
is 2
.
Upvotes: 1