是在for循环的第一个语句中声明的变量是作用域还是特殊处理的?

时间:2017-09-17 00:01:16

标签: javascript syntax binding scope specifications

这两个例子之间是否存在任何(并且我的意思是任何)差异,如同键入的那样 - 甚至是一个微妙的例子?

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

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

我似乎记得我读过的一些评论,它的行为略有不同,但就我所知,foo在两种情况下仍然是功能范围的。有什么区别?

(我试图通读ECMA-262 13.7.4,但结果有点过头了。)

1 个答案:

答案 0 :(得分:3)

是的,有区别。

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