在javascript中函数定义的变量作用域问题:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript">
var num=2;
function test_1(){
alert(num)
}
</script>
</head>
<body>
<button οnclick="test_1()">点击</button>
</body>
</html>
在上面的运行结果中很容易理解num的输出结果为2,那么将全局变量num改为函数中的局部变量如下呢
<script type="text/javascript">
var num=2;
function test_1(){
alert(num)
var num=2;
alert(num)
}
</script>
那么在函数中的第一次num的值会是undefined,第二次输出的num会是2,可见函数中变量的作用域是整个函数的生命周期,即相当于方法的最开始定义。并且局部变量尽量不要和全局变量同名,其实在本质上上面的函数中局部变量的定义等价于如下:
<script type="text/javascript">
//var num=3;
function test_1(){
var num;
alert(num)
num=2;
alert(num)
}
</script>
由以上可总结为变量定义了一定赋初值,局部变量尽量不要和全局变量同名。