var a = a || 4 // var a is evaluated at compile time, so a is undefined here
window.a = window.a || 4 // window.a is simply undefined
window.a = a || 4 // no var a, therefore the variable doesn't exist, = reference error
a = a || 4 // again, no var, reference error
的var
语句声明在最近的封装范围的变量/功能并将其设置为undefined
。当没有var
时,根本没有声明变量/函数。因此参考错误。
一些例子。
function
声明:
foo(); // works
function foo() {}
bar(); // TypeError: undefined is not a function
var bar = function(){};
var
声明:当然
function test(foo) {
if (foo) {
var bar = 0; // defined at compile time in the scope of function test
} else {
bar = 4; // sets the bar above, not the global bar
}
return bar;
}
console.log(test(false)); // 4
console.log(bar); // ReferenceError
这里的差异是对象和未申报对象上未定义的属性。为什么在编译时未定义,但在运行时未声明? – Raynos 2010-12-10 14:46:22
'var'语句在最近的封装范围中声明变量并将其设置为'undefined'。当没有'var'时,根本没有声明变量。因此参考错误。 – 2010-12-10 14:48:19
不错的一个我不知道'var bar = 0'是在编译时定义的函数范围。这就是为什么我只需要一个'var'语句而不是两个 – Raynos 2010-12-10 14:49:50