ES6 为什么在循环中定义时可以重新分配常量

ES6 why can I reassign a constant when defined in a loop

我正在尝试一些毫无意义的逻辑以更好地理解 ES6,并且在定义常量时注意到一个奇怪的事件。

似乎可以在循环中定义常量赋值:

        "use strict";

        for(const i=0;i<10;i++){ //seting constant in loop
            console.log(i); //is reassigned and incremented 0,1,2,3...
        }


        const e = 0; //setting constant outside loop
        for(;e<10;e++){ //cannot reassign constant
            console.log(e);
        }

这是预期的行为吗?任何人都可以阐明为什么会发生这种情况,循环中的声明是否不同?


更新自 Statements/const

This declaration creates a constant that can be global or local to the function in which it is declared. Constants are block-scoped.

当你修改一个"immutable binding"时,current draft只会在严格模式下抛出:

正如@kangax 指出的那样,常量的重新分配应该总是抛出错误,因为 const 创建一个带有 strict 标志的 "immutable binding" (here):

If IsConstantDeclaration of d is true, then

Call env’s CreateImmutableBinding concrete method passing dn and true as the arguments.

then:

SetMutableBinding (N,V,S) ...

  1. Else if the binding for N in envRec is a mutable binding, change its bound value to V.
  2. Else this must be an attempt to change the value of an immutable binding so if S is true throw a TypeError exception.

然而,节点只在严格模式下抛出:

"use strict";

const e = 0;
e = 42;  // SyntaxError: Assignment to constant variable.

(不清楚为什么这是"SyntaxError")...

在非严格模式下,对常量的赋值会被静默忽略:

const e = 0;
e = 42;
console.log(e); // 0

使用带有 --harmony 标志的节点 v0.10.35 进行测试。