Object Creation Expressions

An object creation expression creates a new object and invokes a function (called a constructor) to initialize the properties of that object. Object creation expressions are like invocation expressions except that they are prefixed with the keyword new:

new Object()
new Point(2,3)

If no arguments are passed to the constructor function in an object creation expression, the empty pair of parentheses can be omitted:

new Object
new Date

When an object creation expression is evaluated, JavaScript first creates a new empty object, just like the one created by the object initializer {}. Next, it invokes the specified function with the specified arguments, passing the new object as the value of the this keyword. The function can then use this to initialize the properties of the newly created object. Functions written for use as constructors do not return a value, and the value of the object creation expression is the newly created and initialized object. If a constructor does return an object value, that value becomes the value of the object creation expression and the newly created object is discarded.

Constructors are explained in more detail in Chapter 9.

Table 4-1 gives the precedence for these expressions. They are all of higher priority than the operators shown in Table 4-2. The expressions listed first have higher precedence than those listed last. Expressions separated by a horizontal line have different precedence levels. The column labeled A gives the expression associativity, which can be L (left-to-right) or R (right-to-left).

Table 4-1. JavaScript expressions

OperatorOperationA
( … )Groupingn/a
… . …Member accessL
… [ … ]Computed member accessL
new … ( … )new (with argument list)n/a
… ( … )Function callL
new …new (without argument list)R

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.