1
<SCRIPT>
var week="hello world";fuction off(){
document.write(week);
var week="hello world";
}
</SCRIPT>
output: undefine
2
<SCRIPT>
week="hello world";
fuction off(){
document.write(week);
var week="hello world";
}
</SCRIPT>
output: undefine
3
<SCRIPT>
week="hello world";
fuction off(){
document.write(week);
week="hello world";
}
</SCRIPT>
output: hello world
javaScript 中的变量分为全局变量和函数变量,全局变量一般在函数fuction的外面,函数变量在函数中。
在变量面前加var,变量为局部变量,不加var为全局变量
在函数中不能直接调用全局变量,所以1中的output为undefine,但可以用另外一种方式在函数中来引用全局变量document(this.week) or document(window.week)
var的意思为初始化定义
所以1中
document.write(week);
var week=1;
等价于
var week;
document.write(week);
week=1;
先执行document.write(week);
week只被初始化了而没有被定义,所以output为undefine
而3中 week直接定义没有加var 没有初始化直接定义,week为全局变量