JavaScript中的全局变量如何工作? [英] How does global variables in JavaScript work?

查看:132
本文介绍了JavaScript中的全局变量如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个JavaScript的新手。我通常用Java编程。我很困惑这个下面的代码片段。

 < script> 
x =foo;

函数栏(p){
if(p){
document.writeln(x =+ x);
} else {
var x =baz;
}
}

bar(baz);

< / script>

当我运行上面的代码时,它会缩小它的打印范围

  x = undefined 

为什么打印undefined,因为x是一个全局变量,它应该打印foo的权利?任何人都可以解释吗?

解决方案


因为x是一个全局变量,它应该打印foo正确


如果它没有被 var x =baz; 在你的函数中进一步声明;由于提升,它会执行函数,就好像你写了一样

 函数栏(p){
var x; // = undefined

if(p){
document.writeln(x =+ x);
} else {
x =baz;




$ b

为了让代码做到你想要的,你可以简单地写 x =baz; 而不是 var x =baz;


I m a newbie to javascript. I usually program in Java. I am confused by this following code snippet.

<script>
 x = "foo";

function bar(p){
  if (p){
    document.writeln("x = " + x);
  } else {
    var x = "baz";
  }
}

bar("baz");

</script>

When I run the above code snipped its printing

 x = undefined

Why does it print undefined, since x is a global variable it should print foo right ? Can anyone explain ?

解决方案

since x is a global variable it should print foo right

It would if it wasn't shadowed by the var x = "baz"; declaration further up in your function; due to hoisting it will execute the function as if you wrote

function bar(p){
  var x; // = undefined

  if (p){
    document.writeln("x = " + x);
  } else {
    x = "baz";
  }
}

To make the code do what you want, you could simply write x = "baz"; instead of var x = "baz";.

这篇关于JavaScript中的全局变量如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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