<html> <head> <title></title> </head> <body> <script> myname = "global"; function func(){ alert(myname);//undefined why? var myname = "local"; alert(myname); } func(); </script> </body> </html>
为什么全局变量有声明myname而在函数体内却获取不到值呢?(可以自己调试看看)
根据《javascript 权威指南》中的说法是,函数体在执行之前有个“预编译”状态,即在执行函数体之前,js首先对函数体中的变量进行了遍历。当“预编译”过程中发现函数体有对函数的声明,那么它会在开头部分首先进行隐式的声明。如下列代码:
<html> <head> <title></title> </head> <body> <script> myname = "global"; function func(){ var myname; //myname=undefined alert(myname); var myname = "local"; alert(myname); } func(); </script> </body> </html>
于是最后就出现了有全局变量,但是无法获取值的原因,因为它在函数体内被重新赋值成局部变量了。
文件下载:http://pan.baidu.com/share/link?shareid=90637&uk=3221702211