2014-05-22 34 views
0

我认识到,在函数内部声明变量时省略var关键字是不好的,因为它会将该变量声明为全局变量,而不是函数级作用域。在JavaScript中定义全局变量时省略var关键字

但是,如果你声明一个全局变量呢?除了风格偏好,有什么理由做

var myvar=0; 

myvar=0; 

我个人比较喜欢前者。

这是我写的一个片段,故意用clobbers创建全局变量,其中的var从死循环中被破坏掉,没有var它只会在Chrome中设置它后才被破坏(在IE11和FF中)要发生的事情,变量没有最初重挫:如果您正在使用strict mode,你应该

<html> 
<title>test javascript variable scope</title> 
<script> 
//var innerHeight = undefined; //declare it here, because it gets hoisted... 
function showlength() { 
    //length is a global object, so this function is aware of it... 
    alert('showlength says its ' + length); 
} 
function showIH() { 
    //length is a global object, so this function is aware of it... 
    alert('showIH says its ' + innerHeight); 
} 

//alert('attach your debugger now'); 
//debugger; 
alert('show the original value of length, it is ' + length);  
showlength(); 
length = "abc"; 
alert('the length is ' + length); 
showlength(); 
alert('the window.length has been clobbered, it is ' + window.length); 
alert('innerHeight is ' + innerHeight); 
showIH(); 
alert('window.innerHeight is clobbered because the initialization has been hoisted, here it is ' + window.innerHeight); 
var innerHeight; //it doesn't matter if you declare it here, or up above... 
innerHeight = innerHeight = "xyz"; 
showIH(); 
alert('innerHeight is ' + innerHeight); 
alert('window.innerHeight is ' + window.innerHeight); 
</script> 
<head> 
</head> 
<body> 
<p>Test some variables here</p> 
</body> 
</html> 
+0

请参阅http://stackoverflow.com/a/1471738/637889 – andyb

+0

我会避免使用一个IIEF创建一个闭包变量只是在该函数内的变量的变量。然后可以在不使用全局变量的情况下在这些函数之间共享变量。 – Quentin

回答

3

,你需要var声明变量。为未声明的变量赋值会导致引用错误(例如尝试读取未声明的变量在严格模式之外)。