[英]The Abstract Relational Comparison Algorithm: Why evaluation order is important?
When I read EcmaScript spesification in The Abstract Relational Comparison Algorithm part have information about "LeftFirst" parameter and also spesification say evauation order is not important primitive type but important Object type. 当我在“抽象关系比较算法”部分中阅读EcmaScript spesification时,具有有关“ LeftFirst”参数的信息,并且spiseification表示评估顺序不是重要的原始类型而是重要的Object类型。 Anyone can explain me what is difference which object first evaluated?
谁能解释我首先评估哪个对象的区别?
http://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5 Ecmascript Spesification (aka ecma-internation.org) section 11.8.5 (The Abstract Relational Comparison Algorithm) http://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5 Ecmascript特化(aka ecma-internation.org)第11.8.5节(抽象关系比较算法)
The Abstract Relational Comparison Algorithm evaluates x < y
, but it is used for several operators, EG x < y
, x > y
, x >= y
, sometimes by flipping the order of the operands. 抽象关系比较算法评估
x < y
,但它用于多个运算符,例如EG x < y
, x > y
, x >= y
,有时通过翻转操作数的顺序来实现。 In the case of x > y
, the spec for the Greater-than operator says: 对于
x > y
, 大于运算符的规范说:
Let r be the result of performing abstract relational comparison rval < lval with LeftFirst equal to false.
令r为在LeftFirst等于false的情况下执行抽象关系比较rval <lval的结果。
LeftFirst doesn't matter for primitives because there are no side-effects when they are coerced to numbers for the comparison. LeftFirst对基元并不重要,因为将它们强制为数字进行比较时没有副作用。 However, for objects there can be side-effects:
但是,对于对象可能会有副作用:
const x = { valueOf: _ => console.log( 'x' ) }; const y = { valueOf: _ => console.log( 'y' ) }; y > x;
The above code logs y
then x
. 上面的代码先记录
y
然后记录x
。 Since it uses the greater-than operator, it uses the Abstract Relational Comparison Algorithm for x < y
with LeftFirst = false
as per the above quote from the spec. 由于它使用大于运算符,因此根据上述规范中的上述引用,
LeftFirst = false
x < y
使用抽象关系比较算法,其中LeftFirst = false
。 If instead it used the same algorithm, but with LeftFirst = true
, then it would end up calling ToPrimitive on x
before calling ToPrimitive on y
, which would cause x
to be logged before y
. 如果改为使用相同的算法,但
LeftFirst = true
,则它将最终在x
上调用ToPrimitive,然后在y
上调用ToPrimitive,这将导致x
在y
之前记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.