<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>菜鸟教程(runoob.com)</title> 
</head>
<body>

<p>局部变量在声明的函数外不可以访问。</p>
<p id="demo"></p>
<script>
myFunction();
document.getElementById("demo").innerHTML = "carName 的类型是:" +  typeof carName;
function myFunction() 
{
    var carName = "Volvo";
}
</script>

</body>
</html>

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>菜鸟教程(runoob.com)</title> 
</head>
<body>

<p>全局变量在任何脚本和函数内均可访问。</p>
<p id="demo"></p>
<script>
var carName = "Volvo";
myFunction();
function myFunction() 
{
    document.getElementById("demo").innerHTML =
        "我可以显示 " + carName;
}
</script>

</body>
</html>

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>菜鸟教程(runoob.com)</title> 
</head>
<body>

<p>
如果你的变量没有声明,它将自动成为全局变量:
</p>
<p id="demo"></p>
<script>
myFunction();
document.getElementById("demo").innerHTML =
    "我可以显示 " + carName;
function myFunction() 
{
    carName = "Volvo";
}
</script>

</body>
</html>

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>菜鸟教程(runoob.com)</title> 
</head>
<body>

<p>
在 HTML 中, 所有全局变量都会成为 window 变量。
</p>
<p id="demo"></p>
<script>
myFunction();
document.getElementById("demo").innerHTML =
    "我可以显示 " + window.carName;
function myFunction() 
{
    carName = "Volvo";
}
</script>

</body>
</html>