Need explaination about scope issue in javascript

2019-02-24 07:40发布

I have this code

var Variable = "hello";

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

say_hello();
alert(Variable);

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 ?

3条回答
看我几分像从前
2楼-- · 2019-02-24 08:01

What you are trying to do is alert a variable before initializing it. What you wanted was: function say_hello() { var variable = "bye"; alert(variable); }

查看更多
该账号已被封号
3楼-- · 2019-02-24 08:04

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";
}

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.

查看更多
女痞
4楼-- · 2019-02-24 08:09

This will give you the expected result. Like others said the var keyword will make 'scope local'. You're defining Variable after you alert it in say_hello so it is undefined. Using the 'global scope' if you assign "bye" inside say_hello you won't get "hello" alerted twice.

var Variable = "hello";

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

say_hello();
alert(Variable);
查看更多
登录 后发表回答