Scopes Chains

作者: 奔跑的Pi | 来源:发表于2015-12-01 09:04 被阅读27次
    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

    相关文章

      网友评论

      • LostAbaddon:长代码可以使用代码块哦,语法是这样的:
        ```code-lang
        blablabla
        ```
        奔跑的Pi:@塔塔酱 好的 谢谢

      本文标题:Scopes Chains

      本文链接:https://www.haomeiwen.com/subject/ltfdhttx.html