为什么在外部作用域中定义时,阴影变量会被评估为未定义?

Bea*_*red 8 javascript variables shadowing

考虑以下代码:

<html><head></head>
<body>
    <script type="text/javascript">
        var outside_scope = "outside scope";
        function f1() {
            alert(outside_scope) ;
        }
        f1();
    </script>
</body>
</html> 
Run Code Online (Sandbox Code Playgroud)

此代码的输出是警报框显示消息"外部范围".但是,如果我稍微修改代码为:

<html><head></head>
<body>
    <script type="text/javascript">
        var outside_scope = "outside scope";
        function f1() {
            alert(outside_scope) ;
            var outside_scope = "inside scope";
        }
        f1();
    </script>
</body>
</html> 
Run Code Online (Sandbox Code Playgroud)

警告框显示消息" 未定义 ".如果在两种情况下都显示"未定义",我本可以理解逻辑.但是,这种情况并没有发生.它仅在第二种情况下显示"未定义".为什么是这样?

在此先感谢您的帮助!

CMS*_*CMS 20

变量需要吊装.这意味着无论变量放置在函数中的哪个位置,它都会移动到定义它的作用域的顶部.

例如:

var outside_scope = "outside scope";
function f1() {
    alert(outside_scope) ;
    var outside_scope = "inside scope";
}
f1();
Run Code Online (Sandbox Code Playgroud)

获取解释为:

var outside_scope = "outside scope";
function f1() {
    var outside_scope; // is undefined
    alert(outside_scope) ;
    outside_scope = "inside scope";
}
f1();
Run Code Online (Sandbox Code Playgroud)

因此,以及JavaScript所具有的仅功能范围,建议在函数顶部声明所有变量,使其类似于将要发生的事情.


jsi*_*ght 12

在第一种情况下,您的代码正在访问全局变量"outside_scope",该变量已初始化为"外部范围".

Javascript具有功能级别范围,因此在第二种情况下,它正在访问函数范围变量"outside_scope",但它尚未在警报框中初始化.所以它显示未定义.


Nos*_*dna 5

JavaScript具有功能范围,而不是块范围.

在第二种情况下,outer_scope的声明被提升到函数的顶部(但是赋值不是).

这是一个很好的例子,说明如果将所有变量声明放在函数顶部,JavaScript代码更容易阅读.你的第二个例子相当于:

function f1() {
    var outside_scope;
    alert(outside_scope);
    outside_scope = "inside scope";
}
Run Code Online (Sandbox Code Playgroud)

你现在可以理解为什么你会"未定义".