是在for循环的第一个语句范围内声明的变量,还是专门处理的变量?

问题描述:

这两个例子之间有没有什么区别(我的意思是任何),因为输入 - 即使是微妙的?是在for循环的第一个语句范围内声明的变量,还是专门处理的变量?

for (var foo = 0; …; …) 
    statement; 

var foo = 0; 
for (; …; …) 
    statement; 

我似乎记得一些评论我读了它的行为巧妙不同,但据我所知道的,foo仍然在这两种情况下的功能范围的。有什么不同?

(我试图通过ECMA-262 13.7.4阅读,但它最终成为了一下我的头。)

+1

'foo'在这两种情况下仍然是函数范围,这是正确的。 – Tomalak

是的,是有区别的。

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

+0

你能详细说明最后两个是不同的吗? – Tomalak

+0

我仍然没有看到第三个例子会如何“错误”。这当然没有错,只是写一样东西的另一种方式。 – Tomalak

+0

@Tomalak我的意思是**错误的假设**:错误的人认为这是如何提升工作。我会重新评论评论。 –