gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 19:49:02 24 4
gpt4 key购买 nike

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

但是,如果您声明一个全局变量怎么办?除了风格偏好之外,还有什么理由这样做

var myvar=0;

myvar=0;

我个人更喜欢前者。

这是我写的一个片段,它故意破坏全局变量,使用 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>

最佳答案

如果您使用strict mode ,你应该是这样,你需要 var 来声明变量。为未声明的变量赋值会导致引用错误(例如尝试在严格模式之外读取未声明的变量)。

关于javascript - 在 JavaScript 中定义全局变量时省略 var 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23816916/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com