为什么在外部作用域中定义时,带阴影的变量的结果为未定义? [英] Why does shadowed variable evaluate to undefined when defined in outside scope?

查看:135
本文介绍了为什么在外部作用域中定义时,带阴影的变量的结果为未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

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

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

The output for this code is that the alert box displays the message "outside scope". 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 have understood the logic if it displays "undefined" in both the cases. But, that is not happening. It displays "undefined" only in the second case. Why is this?

提前感谢您的帮助!

推荐答案

在第一种情况下,您的代码将访问已初始化为外部作用域"的全局变量"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.

这篇关于为什么在外部作用域中定义时,带阴影的变量的结果为未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆