简体   繁体   中英

What do people mean when they say “object literal” in JavaScript?

I know that most everything is an object in JavaScript. When people say "object literal," do they mean an object like this?

var thing = {
   'foo': 'bar'
   , 'baz': 'foo'
   , 'bar': 'baz'
};

Yes, that's exactly what object literal means. A definition of a javascript object which may contain comma separated definition of properties, functions, ...

Object literals are formed using the following syntax rules:

  • A colon separates property name from value.
  • A comma separates each name/value pair from the next.
  • There should be no comma after the last name/value pair. Firefox won't object if you add it, but Internet Explorer will trigger an error: 'Expected identifier, string or number'.

An object literal is a way to declare an object.

You would write

var myObject = {}; // with or without members

instead of

var myOject = new Object();

You can also use array literals:

var myArray = [];

instead of

var myArray = new Array(); // with or without members

It's shorter, of course but it also bypasses the constructor so it's supposed to be more efficient.

It's supposed to represent a notational delineation. When they say 'object literal', they mean 'object literal notation'. There are various ways to make an object. This is the most straightforward approach.

Yes.

In the object literal notation, an object description is a set of comma-separated name/value pairs inside curly braces. The names can be identifiers or strings followed by a colon.

Yes, more or less. The "literal" is the source-code representation of the object; so, just the part from { to } , not the rest of the declaration.

A good reference: https://developer.mozilla.org/en/JavaScript/Guide/Values,_Variables,_and_Literals#Object_Literals .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM