Javascript object initialization and evaluation order

浪子不回头ぞ 提交于 2019-11-28 07:19:37

问题


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?

(By experiment, it's {foo: 2, bar: 1}, but I worry whether this is implementation-specific.)


回答1:


See ECMAScript section 11.1.5 defining how the ObjectLiteral production is parsed.

In particular:

PropertyNameAndValueList , PropertyName : AssignmentExpression is evaluated as follows:

  1. Evaluate PropertyNameAndValueList.

  2. Evaluate PropertyName.

  3. Evaluate AssignmentExpression.

...

Where (1) is a recursive definition.

This means the leftmost item in an object literal will get evaluated first, and so {foo: 2, bar: 1} is indeed spec-mandated.




回答2:


They are evaluated in the order they are written.



来源:https://stackoverflow.com/questions/17437965/javascript-object-initialization-and-evaluation-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!