是在for循环的第一个语句范围内声明的变量,还是专门处理的变量?
问题描述:
这两个例子之间有没有什么区别(我的意思是任何),因为输入 - 即使是微妙的?是在for循环的第一个语句范围内声明的变量,还是专门处理的变量?
for (var foo = 0; …; …)
statement;
和
var foo = 0;
for (; …; …)
statement;
我似乎记得一些评论我读了它的行为巧妙不同,但据我所知道的,foo
仍然在这两种情况下的功能范围的。有什么不同?
(我试图通过ECMA-262 13.7.4阅读,但它最终成为了一下我的头。)
答
是的,是有区别的。
for (var foo = something; …; …)
statement;
等同于:
var foo; // hoist foo (declare it at top)
for (foo = something; …; …) // but doesn't assign the value at top, it will assign it where it was before the hoisting
statement;
,但不等同于:
var foo = something; // wrong assumption: it should not move the assignemet to top too, it should move just the declaration
for (; …; …)
statement;
证明:
1-
如果变量未声明的错误将被抛出:
console.log(foo);
2-
如果变量从未赋值,它的值是undefined
:
var foo;
console.log(foo);
3-
移动声明到顶部(曳引),但不赋值:
console.log(foo); // undefined value but doesn't throw an error
var foo = "Hello, world!";
所以它等效于:
var foo; // declared first so it doesn't throw an error in the next line
console.log(foo); // undefined so the assignment is still after this line (still at the same place before hoisting)
var foo = "Hello, world!"; // assignment here to justify the logged undefined value
'foo'在这两种情况下仍然是函数范围,这是正确的。 – Tomalak