Scopes Chains

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:

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:

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:


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:

scope chains

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容