How to use anonymous objects 2007-03-22

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 ” + + “ 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.label + “ ” + params.isFunny;

// More code… }

doSomething({id : 2, label : “name”, isFunny: true}); [/source]

How to extend javascript classes 2007-03-21

The intrinsec objects of javascript (String, Number, Date, etc) are missing a lot of handy methods. God knows why. Example, you don't have a trim() function on a String object. Maybe the developers thought that it was easy enough to write theString.replace(/^\s|\s$/g, “”) to trim a string but that's not the kind of ugly code I want to see everywhere in my projects. It's unesthetical. To do this, I have to use prototype.

So I want to add a trim() method to all my objects that are String class.


String.prototype.trim = function() { return this.replace(/^\s|\s$/g, “”); }



Special note : I don't want you to copy/paste that code. It's for the purpose of the demonstration only.

I can do the same thing for every objects wheter they are intrinsic javascript classes, third-party classes or my own classes.

What are javascript prototypes? (short answer for advanced javascripters) 2007-03-21

[I've also written a longer answer for beginners] 

Prototypes can extend any class you want by adding a property or a method. By calling,

[source:javascript] String.prototype.alertMe = function() { alert(this); } [/source]

you are adding the method alertMe() to every String object of your application.

It uses less memory because javascript creates only one instance of the function and uses references to it.

Short answer done!

5 reasons to write object-oriented (oo) javascript 2007-03-19

To write hard as a rock javascript, the first thing you need to do is to object-orient your code. I do not mean to have a class structure that could stand the passage of a sandstorm in the Sahara but a light and useful structure that will let you work elegantly.

This article does not explain the techniques behind the reasons. It is written for the sake to make you change the way you develop in javascript.

Go read this article if you want to see some code.

1. Packages/namespaces : no more 152 characters prefixes to ensure uniqueness

Packages/namespaces (packages = java, namespaces = .NET) are not the greatest thing since slice bread (did you forget about kool-aid?) but they are the handiest solution to avoid methods, objects or constants to have the same name. I give you a simple example.

I have two methods :

  • one that truncates a string of its last character (who wants to do that???)
  • one that truncates a number of its decimals
I would write these methods :
  • truncate(theString)
  • truncate(theNumber)
The problem is that they have both the same signature. How can javascript differenciate the two and call the good one? It can't.

With packages/namespaces, I could have the following signatures to differenciate them.

  • com.CompanyName.String.truncate(theString);
  • com.CompanyName.Number.truncate(theString);
Of course, I could have done it a million ways (extending String and Number objects, give them different names, etc) but for the purpose of the demonstration, I have done it that way.

2. Work locally : forget about global variables circa 1987

Global variables are prohibited since 1992 by GVIP (Global Variables International Police). Every variable of that type is seeked and destroyed by them. With javascript, the difference is that a global variable is not “global to the entire application” but global to a page. That's the gray zone. There's no strict law against that and people think that it's OK to do so. They are wrong! A web application that heavily relies on javascript would have dozens of dozens of global variables and would soon become a 3500 pieces puzzle.

Object-oriented javascript allows you to work locally on each variable by making it static (shared for .NETters) or using closures (subject of another article soon!) within an object.

3. Ajax : be a part of web2.0

You want to be the next golden-boy of the web2.0 era? Better start using Ajax now. But wait! Ajax is a mess with all of those callback, failure and timeout functions here and there. Will it stop me from being a billionaire?

No. Object-oriented javascript permits you to stay clean by encapsulating all those ugly functions in objects. Hey, here you'll need closures too! The last step you need to do is to stay away from drugs. Drugs are bad for your health and they could kill you before you reach your goal. Did I mention “Don't run with scissors”?

4. Inheritance : for greater powers

I wouldn't recommend you to use inheritance just to impress women. Inheritance is far too complex for its benefits (you won't get more women) unless you have a very complex application. And by complex, I mean more complex than building a space shuttle.

Now you are warned. Inheritance is the “most common” principle behind object-oriented and can be implemented in javascript. No, you won't have the handy extend/inherits or whatever statement in oo language. Maybe this will keep you from over-designing your code so it's not that bad after all.

5. The future : javascript is already there

Javascript is a step ahead of a lot of programming languages. Sure, it is copied on such and such obscure language but it is the most widely known language that first used closures, functionnal programming, untyped variables and so on.

Java programmers, in their glass tower, think of javascript as a disordered mutant of their beloved language. They are wrong! Javascript only shares its syntax. The most recent versions of Java are now implementing closures and varargs. Looks like the natural selection from Evolution theory has done it again.

If you want to see code for doing object-oriented javascript, read this article.