为什么在外部范围内定义时

为什么在外部范围内定义时

本文介绍了为什么在外部范围内定义时,阴影变量评估为未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

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

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

The output for this code is that the alert box displays the message "outsidescope". But, if I slightly modify the code as:

<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>

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

the alert box displays the message "undefined". I could haveunderstood the logic if it displays "undefined" in both the cases. But, thatis not happening. It displays "undefined" only in the second case. Why is this?

预先感谢您的帮助!

推荐答案

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

In the first case, your code is accessing the global variable "outside_scope", which has been initialized to "outside scope".

Javascript 具有函数级作用域,因此在第二种情况下,它访问的是函数作用域变量outside_scope",但在出现警告框时尚未初始化.所以它显示未定义.

Javascript has function level scope, so in the second case it is accessing the function scoped variable "outside_scope", but it has not yet been initialized at the time of the alert box. So it displays undefined.

这篇关于为什么在外部范围内定义时,阴影变量评估为未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 16:35