我了解有关本地和全局变量的基础知识,但有没有人可以解释这两个代码示例之间的差异?
var elements = document.querySelectorAll('.classname');
for (var i = 0; i < elements.length; i++) {
// do something
}
和
var elements = document.querySelectorAll('.classname');
for (i = 0; i < elements.length; i++) { // <-- removed "var" before "i = 0"
// do something
}
答案 0 :(得分:1)
使用var
关键字,没有&#34;块&#34;范围,所以声明是&#34;功能&#34;范围或&#34;全球&#34;。在循环或if
语句的true / false分支中声明变量的事实不会创建仅限于该代码块的变量。这与大多数编译语言完全不同。
ECMAScript 2016(a.k.a。ES6)介绍&#34; block&#34;范围包含let
关键字。
因此,如果省略var
关键字并在函数中创建一个新变量,那么该变量将变为全局变量,因为JS运行时并不知道您希望它的作用域。
以下是一些例子:
// Outside of functions, the var keyword creates global variables
var g = "global";
function foo(){
// Inside of functions, the var keyword creates "local" or function scoped variables
var l = "local";
// But, omitting the "var" keyword, whereever you do it, creates a global
oops = "global";
// But, creating a function scoped variable of the same name as a variable in a higher
// scope, just hides the one from the higer scope as long as the code runs in the smaller
// scope:
var g = "local";
// Other than global and function, the var keyword does not create "block" scope:
if(true){
var x = "surprise!";
}
// Now, we'll see what we get when we are in the local scope:
console.log(g); // "local", not "global" because smaller scope prevails
console.log(l); // "local";
console.log(oops); // "global"
console.log(x); // "surprise!" because x has function scope, not block
}
foo();
// Now, we'll see what is available back in the global scope:
console.log(g); // "global" because now we are in the global scope
console.log(typeof l); // It's an error to try to access directly, type is undefined
console.log(oops); // "global" because we omitted var and it became global
console.log(typeof x); // It's an error to try to access directly, type is undefined
&#13;