JavaScript 中单个 Var 声明中的重复标识符

Repeated Identifiers in a Single Var Declaration in JavaScript

我注意到 Google 的 Closer Compiler 可能会将带有变量的语句打包到前面的 var 声明中,从而在该声明中产生重复的标识符。这是我得到的输出示例:

    var a = Ak - Aj, 
        b = Bk - Bj, 
        c = Math.sqrt(a*a+b*b), 
        a = a / c,
        b = b / c

注意 ab 是如何在同一 var 声明中重新声明和分配新值的。此外,看起来 ab 的旧值在它们的第二次初始化中使用。这会在 ES5 / ES6 中产生明确定义的行为吗?

EcmaScript 规范在 section on var:

A var statement declares variables that are scoped to the running execution context's VariableEnvironment. Var variables are created when their containing Lexical Environment is instantiated and are initialized to undefined when created. Within the scope of any VariableEnvironment a common BindingIdentifier may appear in more than one VariableDeclaration but those declarations collectively define only one variable. A variable defined by a VariableDeclaration with an Initializer is assigned the value of its Initializer's AssignmentExpression when the VariableDeclaration is executed, not when the variable is created.

换句话说,一个变量可能在 var 语句中出现多次,但相关变量仍然只会被声明一次,并且该声明将在任何代码(在该范围内)被声明之前发生已执行(a.k.a。"hoisting")。初始化将按正常执行顺序执行。

因此,根据规范,您的示例代码等同于:

var a, b, c;
a = Ak - Aj;
b = Bk - Bj; 
c = Math.sqrt(a*a+b*b); 
a = a / c;
b = b / c;