Scopes Chains

Scopes Chains_第1张图片
Scope Chain

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:

Scopes Chains_第2张图片
scope tree

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:

Scopes Chains_第3张图片
Scope chain

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:


Scopes Chains_第4张图片
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:

Scopes Chains_第5张图片
scope chains

** reference : **
scope-chains-closures
picture

你可能感兴趣的:(Scopes Chains)