javascript 对于全局声明的变量返回未定义[重复]

2024-01-03

我是 javascript 的初学者。我有一个疑问。我的代码如下所示。当我运行此命令时,第一个警报框显示“未定义”。我不明白为什么?非常感谢..

<html>
<head>
<script type="text/javascript">
var a = 123;
   function foo()
   {
     alert(a);
     var a = 890;
     alert(a);
   }
     foo();
     alert(a); 
</script>
</head>
<body>
</body>
</html>

这是因为之后hoisting but 执行前, your foo()函数内部看起来像:

function foo() {
    var a; // declaration hoisted to top
    alert(a); // the local var is 'undefined' at this point
    a = 890; // assignment operation not hoisted
    alert(a);
}

在此处阅读有关吊装的更多信息:

  • http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
  • http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/ http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

javascript 对于全局声明的变量返回未定义[重复] 的相关文章

随机推荐