Are Javascript Object Properties assigned in order?

前端 未结 5 895
深忆病人
深忆病人 2020-12-03 14:11

Say I have an object which assigns properties based off the return value of a function:

var i = 0;

var f = function() { return ++i; }

var foo = {
                  


        
5条回答
  •  孤城傲影
    2020-12-03 14:38

    From the ECMAScript 6 wiki, which will define the new version of JS:

    When a scope (Block, FunctionBody, Program, ModuleBody, etc.) is entered, the variables declared by all immediately contained function and class declarations are bound to their respective functions and classes. Then all class bodies are executed in textual order. A class body defines and initializes class-wide properties once when the class definition is evaluated. This includes properties on the constructor function (the “class” itself) and on its prototype property. These initializations happen in textual order.

    Your source has arrived! JavaScript object properties are initialized in textual order on objects. Arrays do not (currently) always follow this rule.

    Source: http://wiki.ecmascript.org/doku.php?id=harmony:classes

    I will edit this post when I find the reference in ECMAScript 5, though I am certain it is there.

    Edit: Found it

    ECMAScript 5 does have it: http://www.ecma-international.org/ecma-262/5.1/#sec-15.2.3.7 .

    If an implementation defines a specific order of enumeration for the for-in statement, that same enumeration order must be used to order the list elements in step 3 of this algorithm.

    This defines the calls to DefineOwnProperty and therefore the position of the properties in the internal table.

提交回复
热议问题