在JavaScript中定义全局变量时省略var关键字

时间:2014-05-22 20:56:53

标签: javascript internet-explorer google-chrome firefox

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

但是,如果你宣布一个全局变量怎么办?除了样式偏好之外,还有什么理由可以做

var myvar=0;

myvar=0;

我个人更喜欢前者。

这是我写的一段故意破坏全局变量的片段,其中变量被搞砸了,没有它只是在你在Chrome中设置它(在IE11和FF中)之后被破坏了吊装似乎没有正在发生,变量最初没有被破坏:

<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>

1 个答案:

答案 0 :(得分:3)

如果您使用的是strict mode,则需要var来声明变量。为未声明的变量赋值会导致引用错误(例如尝试读取未声明的变量超出严格模式)。