Creating Objects
Objects can be created with object literals, with the new keyword, and (in ECMA Script 5 ) with the
Object.create() function. The
subsections below describe each technique.
Object Literals
The easiest way to create an object is to include an object literal in your JavaScript code. An object literal is a comma-separated list of colon-separated name:value pairs, enclosed within curly braces. A property name is a JavaScript identifier or a string literal (the empty string is allowed). A property value is any JavaScript expression; the value of the expression (it may be a primitive value or an object value) becomes the value of the property. Here are some examples:
varempty={};// An object with no propertiesvarpoint={x:0,y:0};// Two propertiesvarpoint2={x:point.x,y:point.y+1};// More complex valuesvarbook={"main title":"JavaScript",// Property names include spaces,'sub-title':"The Definitive Guide",// and hyphens, so use string literals"for":"all audiences",// for is a reserved word, so quoteauthor:{// The value of this property isfirstname:"David",// itself an object. Note thatsurname:"Flanagan"// these property names are unquoted.}};
In ECMAScript 5 (and some ECMAScript 3 implementations), reserved words may be used as property names without quoting. In general, however, property names that are reserved words must be quoted in ECMAScript 3. In ECMAScript 5, a trailing comma following the last property in an object literal ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access