抽象关系比较算法:为什么评估顺序很重要?

The Abstract Relational Comparison Algorithm: Why evaluation order is important?

当我在抽象关系比较算法部分阅读 EcmaScript 规范时,有关于 "LeftFirst" 参数的信息,而且规范还说疏散顺序不是重要的原始类型,而是重要的对象类型。 任何人都可以解释一下哪个对象首先评估的区别是什么?

http://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5 Ecmascript 规范(又名 ecma-internation.org)第 11.8.5 节(抽象关系比较算法)

抽象关系比较算法评估 x < y,但它用于多个运算符,例如x < yx > yx >= y,有时通过翻转操作数的顺序。在 x > y 的情况下,spec for the Greater-than operator 表示:

Let r be the result of performing abstract relational comparison rval < lval with LeftFirst equal to false.

LeftFirst 对于基元来说无关紧要,因为当它们被强制转换为数字进行比较时没有副作用。但是,对于对象,可能会有副作用:

const x = { valueOf: _ => console.log( 'x' ) };
const y = { valueOf: _ => console.log( 'y' ) };

y > x;

以上代码记录 y 然后 x。由于它使用大于运算符,因此根据规范中的上述引述,它使用 x < yLeftFirst = false 的抽象关系比较算法。相反,如果它使用相同的算法,但使用 LeftFirst = true,那么它最终会在 x 上调用 ToPrimitive,然后再在 y 上调用 ToPrimitive,这将导致记录 xy.

之前