【发布时间】:2014-05-22 20:56:53
【问题描述】:
我意识到在函数内声明变量时省略 var 关键字是不好的,因为它会将变量声明为全局变量,而不是函数级范围。
但是,如果您要声明一个全局变量怎么办?除了风格偏好,还有什么理由这样做
var myvar=0;
对比
myvar=0;
?
我个人更喜欢前者。
这是我写的一个 sn-p,它故意破坏全局变量,使用 var 从一开始就破坏它,没有 var,它只有在 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>
【问题讨论】:
-
我会避免使用变量,而是使用 IIEF 来创建一个带有该函数内部变量的闭包。然后可以在函数之间共享该变量,而无需使用全局变量。
-
在非严格模式下省略 var 关键字不会创建变量。它在全局对象上创建了一个普通的旧属性。相当于
globalThis.variableName = 'foo'。
标签: javascript internet-explorer google-chrome firefox