Visit Mozilla.org

Core JavaScript 1.5 Guide:Creating New Objects:Using Object Initializers

From MDC


[edit] Using Object Initializers

In addition to creating objects using a constructor function, you can create objects using an object initializer. Using object initializers is sometimes referred to as creating objects with literal notation. "Object initializer" is consistent with the terminology used by C++.

The syntax for an object using an object initializer is:

var obj = { property_1:   value_1,   // property_# may be an identifier...
            2:            value_2,   // or a number...
            ...,
            "property_n": value_n }; // or a string

where obj is the name of the new object, each property_i is an identifier (either a name, a number, or a string literal), and each value_i is an expression whose value is assigned to the property_i. The obj and assignment is optional; if you do not need to refer to this object elsewhere, you do not need to assign it to a variable. (Note that you may need to wrap the object literal in parentheses if the object appears where a statement is expected, so as not to have the literal be confused with a block statement.)

If an object is created with an object initializer in a top-level script, JavaScript interprets the object each time it evaluates an expression containing the object literal. In addition, an initializer used in a function is created each time the function is called.

The following statement creates an object and assigns it to the variable x if and only if the expression cond is true.

if (cond) x = {hi:"there"};

The following example creates myHonda with three properties. Note that the engine property is also an object with its own properties.

var myHonda = {color:"red",wheels:4,engine:{cylinders:4,size:2.2}};

You can also use object initializers to create arrays. See Array Literals.

JavaScript 1.1 and earlier. You cannot use object initializers. You can create objects only using their constructor functions or using a function supplied by some other object for that purpose. See Using a Constructor Function.

« Previous Next »