简体   繁体   English

Javascript对象初始化和评估顺序

[英]Javascript object initialization and evaluation order

If I write 如果我写

var a = [1,2];
var b = {
  foo: a.pop(),
  bar: a.pop()
};

What is the value of b , according to the specification? 根据规范, b的价值是多少?

(By experiment, it's {foo: 2, bar: 1} , but I worry whether this is implementation-specific.) (通过实验,它是{foo: 2, bar: 1} ,但我担心这是否是特定于实现的。)

See ECMAScript section 11.1.5 defining how the ObjectLiteral production is parsed. 请参阅ECMAScript第11.1.5节,定义如何解析ObjectLiteral生产。

In particular: 特别是:

PropertyNameAndValueList , PropertyName : AssignmentExpression is evaluated as follows: PropertyNameAndValueListPropertyNameAssignmentExpression的计算方法如下:

  1. Evaluate PropertyNameAndValueList. 评估PropertyNameAndValueList。

  2. Evaluate PropertyName. 评估PropertyName。

  3. Evaluate AssignmentExpression. 评估AssignmentExpression。

... ...

Where (1) is a recursive definition. 其中(1)是递归定义。

This means the leftmost item in an object literal will get evaluated first, and so {foo: 2, bar: 1} is indeed spec-mandated. 这意味着对象文字中最左边的项目将首先被评估,因此{foo: 2, bar: 1}确实是指定的。

它们按照它们的编写顺序进行评估。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM