2010-12-10 88 views
0

任何人都可以解释这一点(在全球范围内码)Javascript来自理分配全局变量

var a = a || 4 // a exists & is 4 
window.a = window.a || 4 // a exists & is 4 
window.a = a || 4 // a is undefined error 
a = a || 4 // a is undefined error 

的区别是这4个作业和为什么一些处理得当,但其他人没有什么之间的解释。

[编辑]这个特殊的例子已经在V8 Chrome控制台上测试过。

回答

4
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 
+0

这里的差异是对象和未申报对象上未定义的属性。为什么在编译时未定义,但在运行时未声明? – Raynos 2010-12-10 14:46:22

+0

'var'语句在最近的封装范围中声明变量并将其设置为'undefined'。当没有'var'时,根本没有声明变量。因此参考错误。 – 2010-12-10 14:48:19

+0

不错的一个我不知道'var bar = 0'是在编译时定义的函数范围。这就是为什么我只需要一个'var'语句而不是两个 – Raynos 2010-12-10 14:49:50