Writing Code with Object Literals

As covered in the sidebar, About Object Literals, there’s more than one way to write any given JavaScript. Script 11.11 is an example of how Script 11.10 can be rewritten to use object literals.

About Object Literals

Standard procedural JavaScript, like what you’ve seen so far, has been in the dot notation format:

var myCat = new Object;
myCat.name = "Pixel";
myCat.breed = "Tuxedo";
myCat.website = "www.pixel.mu";
function allAboutMyCat() {
    alert("Can I tell you about my cat?");
    tellMeMore = true;
}

Where in object literal format, that same code would be something like this:

var myCat = { name : "Pixel", breed : "Tuxedo", website: "www.pixel.mu", allAbout : function() { alert("Can I tell you about my cat?"); ...

Get JavaScript and Ajax for the Web: Visual QuickStart Guide, Seventh 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.