How to use anonymous objects
I don’t know how to call it and I don’t even know if it has a name. I thought a moment about calling it Mistigri but I already have a cat with that name. I decided to call it anonymous object.
How?
[source:javascript]
var ao = {
name : “Anonymous Object”,
possibleName : “Mistigri”,
presentYourself : function() {
alert(”Hi! My name is ” + this.name + ” but they thought of calling me ”
+ this.possibleName + “.”);
}
ao.presentYourself();
[/source]
By running the code below, you should see a message box with Hi! My name is Anonymous Object but they thought of calling me Mistigri. Isn’t it wonderful?
What can I do with that?
For the moment, I haven’t found a lot of uses for anonymous objects. If you know more, leave a comment and I will add yours to mine. Maybe we’ll end up with two and a half diffrent uses.
Still, I am using it to create enumerations (enum).
[source:javascript]
var DisplayType = {
big : 0,
medium : 1,
small : 2
}
var display = DisplayType.big;
alert(display);
[/source]
This is very useful instead of creating “constants” with different name.
[source:javascript]
var DISPLAY_TYPE_BIG = 0;
var DISPLAY_TYPE_MEDIUM = 1;
var DISPLAY_TYPE_SMALL = 2;
[/source]
Second use
Nicolás Sanguinetti pointed to me another use of anonymous objects.
Saying you have a lot of possible parameters to pass to a method. Instead of having them all list, you use an anonymous object as parameters and the programmer decides which one he will use.
Instead of
[source:javascript]
function doSomething(id, name, label, age, fatherName, brotherName, motherName, grandmaName, isFunny, isShy)
{
var concat = id + ” ” + label + ” ” + isFunny;
// More code…
}
doSomething(2, null, “name”, null, null, null, null, null, true, null);
[/source]
you have
[source:javascript]
function doSomething(params)
{
var concat = params.id + ” ” + params.label + ” ” + params.isFunny;
// More code…
}
doSomething({id : 2, label : “name”, isFunny: true});
[/source]


Well, configuration options for methods. The Prototype and Script.aculo.us JS frameworks use this extensively.
For example, in script.aculo.us, when you want something to fade from one color to another, you do something like Effect.Fade(”my_dom_id”, { from: “#000000″, to: “#ff0000″ });
(I don’t remember the exact syntax, but the idea is there :))
These guys are actually called object literals ( http://en.wikipedia.org/wiki/Object_literal ).