Scopes Chains
Nesting
function someFunc() { function inner() { } }
inner is a nested lexical scope inside the lexical scope of someFunc.
if (true) { while (false) { } }
The while is a nested block scope inside the block scope of if.
function someFunc() { if (true) { } }
The if is a nested block scope inside the lexical scope of someFunc.
Scope Tree
function someFunc() { function inner() { } function inner2() { function foo() { } } }
Produce tree as follow:
inner scopes can access outer scope's variables, not vice-versa. thus, forms a Scope Chains.
function foo () { var bar; function zip () { var quux; } }
the scope chain as follow:
following the arrows, we can see zip() has access to var bar, but not the other way around.
Global Scope
Global scope sits at the top of every scope chain:
Global Scope
Javascript runtime follows these steps to assign a variable:
1.search within the current scope.
2.if not found, search in the immediately outer scope.
3.if found, go to 6.
4.if not found, repeat 2. Until the Global Scope is reached.
5.if not found in Global Scope, Create it.
6.assign the value.
Cosider the following example:
function someFunc() { var scopeVar = 1; function inner() { foo = 2; } }
following above algorithm, foo became a variable in the Global Scope.
Shadowing
function someFunc() { var foo = 1; function inner() { var foo = 2; } }
the foo inside inner() is said to Shadow the foo inside someFunc().Shadow means that the inner() scope only has access to its own foo.
function foo () { var bar; quux = 10; function zip () { var quux = 20; } }
the scope chains:
** reference : **
scope-chains-closures
picture