A few months ago I came across a post by Dustin Diaz titled JSON for the masses. As some comments in the post suggest, his examples are not actually JSON (commonly used as a data interchange format) because the member names are not quoted. But the main point of the article is actually on JavaScript’s “object literal notation”, a method of creating object literals.
It’s quite simple. Douglas Crockford writes:
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.
Thus, you can create an object like this:
var myObject = {
name: "Peter Foti",
'course': 'JavaScript',
grade: 'A',
level: 3
};
At first, I found this style somewhat awkward. But the more I use it, the more natural it seems. It’s also quite useful for creating self-invoking objects or namespaces to keep your global objects to a minimum. For example:
var FOTI = {
return {
name : "Peter Foti",
init : function() {
alert('Initializing!');
}
};
}(); // Self invoking
window.onload = FOTI.init;




2 users commented in " JavaScript Object Literal Notation "
Follow-up comment rss or Leave a Trackbacka question about parameters in the object literal notation. can you only have literals as parameters or you also have parameter values be functions like so:
name = {
parameter1 : document.getElementById(‘id’);
function1 : function() {
code…
}
}
Please reply
THANKS THANKS THANKS
Yes, you can have parameter values as functions. They can hold anything a normal variable can hold… strings, numbers, booleans, arrays, or objects (am I forgetting anything?). Here’s a quick example:
Leave A Reply