Are javascript elements initialized in a specific order?

I have a function like this:

parsers[1] = function(buf) { return { type: "init", name: buf.readUTF8String(), capacity: buf.readUInt32(), port: buf.readUInt16() }; } 

Do I have a guarantee that name , capacity and port will be initialized one by one? Otherwise, the buffer will be read in the wrong order.

I could of course retreat:

 parsers[1] = function(buf) { var ret = {type: "init"}; ret.name = buf.readUTF8String(); ret.capacity = buf.readUInt32(); ret.port = buf.readUInt16(); return ret; } 
+6
source share
2 answers

Thanks to @joews comment, I can answer my question.

From reference 11.1.5 Object initializer :

Syntax

ObjectLiteral:

  • {}

  • {PropertyNameAndValueList}

  • {PropertyNameAndValueList,}

Property NameAndValueList:

  • PropertyAssignment

  • PropertyNameAndValueList, PropertyAssignment

In short, the object constructor takes as arguments nothing, a list of initialization values ​​or a list of initialization values, followed by a comma.

This list of initialization values ​​consists of a PropertyAssignment or a list of initialization values ​​followed by a PropertyAssignment , which basically means a list of PropertyAssignment by recursion.

Now the question is in the last PropertyNameAndValueList , PropertyAssignment , is there a specific order in which both components are evaluated?

Production PropertyNameAndValueList: PropertyNameAndValueList, PropertyAssignment is evaluated as follows:

  • Let obj be the result of evaluating PropertyNameAndValueList.

  • Let propId be the result of evaluating the PropertyAssignment.

  • ...

Order will be guaranteed if 2. necessarily follows 1. ..

From 5.2 Algorithm Agreements :

A specification often uses a numbered list to indicate steps in an algorithm. These algorithms are used to accurately determine the required semantics of ECMAScript language constructs. Algorithms do not involve the use of any particular implementation technique. In practice, there may be more efficient algorithms for implementing this function.

...

For clarity of expression, the steps of the algorithm can be divided into consecutive substeps.

So, the expected initialization order is element by element from which I can assemble.

+3
source

As in many other languages, I will not rely on any “order” of object properties and how they are initialized or assigned values.

If an “external” order is required, I will try to achieve this with a kind of comparison of these properties.

0
source

Source: https://habr.com/ru/post/986820/


All Articles