需要在javascript中解释范围问题 [英] Need explaination about scope issue in javascript

查看:60
本文介绍了需要在javascript中解释范围问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码

var Variable = "hello";

function say_hello ()
{
    alert(Variable);
    var Variable = "bye";
}

say_hello();
alert(Variable);

现在,当我第一次读到这段代码时,我认为它会两次发出hello警告,但是我得到的结果是第一次警告未定义,第二次警告你好。有人可以向我解释原因吗?

Now, when I first read this code, I thought it will alert "hello" two times, but the result I get is that it alerts "undefined" the first time, and "hello" second time. can someone explains to me why ?

推荐答案

在JavaScript中,所有 var 函数中的声明被视为它们出现在函数体的最顶部,无论它们实际位于代码中的哪个位置。因此,你的函数被解释为它是这样写的:

In JavaScript, all var declarations in a function are treated as if they appeared at the very top of the function body, no matter where they actually are in the code. Your function therefore was interpreted as if it were written like this:

function say_hello() {
  var Variable;
  alert(Variable);
  Variable = "bye";
}

请注意,只是声明被解释为办法;初始化表达式发生在 var 实际位于代码中的位置。因此,您的函数定义了一个名为Variable的局部变量,该变量隐藏了更多的全局变量。在 alert()运行时,该变量尚未初始化。

Note that it's just the declaration that's interpreted that way; the initialization expression happens where the var actually sits in your code. Thus, your function defined a local variable called "Variable", which hid the more global one. At the point the alert() ran, the variable had not been initialized.

这篇关于需要在javascript中解释范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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