在Javascript中作用域是由函数划分的。 //设置全局变量foo var foo = "test"; if(true){ var foo = "new foo"; } //此时foo为"new test" alert(foo == "new foo"); function test(){ var foo = "old test"; } //调用时,foo只在函数作用域内起作用 test(); //foo还是等于"new test" alert(foo == "new test"); 基于Javascript的一个特性是,所有基于全局作用域的变量都是window对象的属性。var test = "test"; alert(window.test == test); 当省略var时,变量默认为全局的,即便是在函数内部出现。function test(){ foo = "test"; } test(); alert(window.foo == "test");