Skip to content Skip to sidebar Skip to footer

Javascript: When Using Object Literal, Does Ordering Of Properties Matters?

Taking the following example from: http://www.phpied.com/3-ways-to-define-a-javascript-class/ var apple = { type: 'macintosh', color: 'red', getInfo: function () {

Solution 1:

The code inside the function is not executed until you call it, and so the property color of this is not evaluated until apple.getInfo() is called.

Edit:

var apple = {
    getInfo: function () {
        returnthis.color + ' ' + this.type + ' apple';
    },
    type: "macintosh",
    color: "red",
    }
}

At this time the apple object is defined, and the getInfo property is a function that will return the properties ``when it is evaluated

apple.getInfo();

The function is now evaluated, and the properties color and type have clearly already been defined at this point

The function obtains the values of these properties when it is evaluated so that if the properties color and type are changed, the return value of the function changes too.

Solution 2:

The function is called after you made the instance. When defined, it is not run, does not try to access the properties, but where you called the getInfo() function, they are all present. In fact, there is no way to run any custom JavaScript code between the interpreter parsing individual properties.

Solution 3:

I was expecting the javascript parser/compiler to fail, since this.color and this.type are not yet defined.

The parser in the compiler doesn't care. JavaScript doesn't evaluate whether a property or variable can be found until the code using it is executed. And in the case of properties, a property that doesn't exist yet just gets created (if you're writing to it) or results in the value undefined (if you're reading from it), so even if your object didn't have color and type properties, the code still wouldn't throw an error. You'd just get the string "undefined undefined apple".

Javascript: when using Object literal, does ordering of properties matters?

Matters? Probably not. Have meaning? Yes, as of ES6 (aka ECMAScript 6 aka ECMAScript 20150), the latest specification. The order of properties in an object initializer determines the order the properties are created, which in turn partially sets the order in which they're visited by for-in loops, the order they show up in Object.keys arrays, etc. (Partially because property names that can coerce to integers are handled differently.) But it's rare for you to care. Details in this answer and this answer (that latter one is mostly about arrays, but touches on non-array objects as well).

Post a Comment for "Javascript: When Using Object Literal, Does Ordering Of Properties Matters?"