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.



var ao = { name : “Anonymous Object”, possibleName : “Mistigri”, presentYourself : function() { alert(“Hi! My name is ” + this.name + “ but they thought of calling me ” + this.possibleName + “.”); }



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.




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]

comments powered by Disqus