javascript为全局声明的变量返回undefind [英] javascript returns undefind for a globally declared variable
本文介绍了javascript为全局声明的变量返回undefind的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是javascript的初学者。我有一个疑问。我的代码是下面给出的。当我运行这个第一个警告框显示undefind。我不明白为什么?非常感谢..
I am a beginer to javascript.I have a doubt.my code is given bellow.when i run this the 1st alert box displaying "undefind".i can not understand why?thanks alot..
<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>
推荐答案
这是因为在提升后但在执行之前,你的 foo()
函数在内部看起来像:
This is because after hoisting but before execution, your foo()
function internally looks like:
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);
}
了解更多关于在这里吊装的信息:
Read more about hoisting here:
- http:// www .adequatelygood.com / 2010/2 / JavaScript-Scoping-and-Hoisting
- http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/
- http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
- http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/
这篇关于javascript为全局声明的变量返回undefind的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文