How to do class functions in javascript (aka static or shared functions) 2007-03-26

One of the really concept of the object-oriented programming is the class functions but they are also known as static functions (Java, php, C++) or shared functions (.NET).

Why using class method?

Class methods help you keeping your code clean by centralizing your functions. Example, you create a calendar object that formats a string from two dates to have readable time difference (example, input : “2007-08-13” and “2007-08-16”, output : “begins august 13th 2007 and ends 3 days later”).

Sure you can create a readableTime(beginDate, endDate) function. First problem is that there may be another function with that name. Second problem? If another programmer works on the code that makes a call to readableTime function, how does he knows that it comes from the javascript file containing the Calendar object?

So, you could create a CalendarreadableTime(beginDate, endDate) function. Great! But what if the object name Calendar changes for BestCalendar? The CalendarreadableTime function won't have the good suffix.

The solution is to use a class function so the call to the readableTime function will look like this : Calendar.readableTime(beginDate, endDate). Nice looking and clean code.

How to create a class function

First, you create a class

[source:javascript] function Calendar() { } [/source]

Second, you add the class function

[source:javascript] function Calendar() { }

Calendar.readableTime = function() { // Code here } [/source]

Then, it's ready to be called in your code

[source:javascript] var cal = new Calendar(); var beginDate = new Date(); var endDate = new Date(); endDate.setDate(endDate.getDate() + 3); // Add three days to endDate

var stringTime = Calendar.readableTime(beginDate, endDate); [/source]

Difference with other languages

In many other languages, your class functions are callable from an instantiated object like this.

[source:javascript] var cal = new Calendar(); var beginDate = new Date(); var endDate = new Date(); endDate.setDate(endDate.getDate() + 3); // Add three days to endDate

// I call cal.readableTime and it doesn't work! var stringTime = cal.readableTime(beginDate, endDate); [/source]

In javascript, it doesn't work because the function readableTime is assigned to the class only and is not referenced in the instances of the class.

To give the access to the readableTime function on the instance of an object is to create the function this way :

[source:javascript] function Calendar() { }

Calendar.readableTime = new function() { // Code here }

// Here's the magic Calendar.prototype.readableTime = Calendar.readableTime; [/source]

By assigning the function to the prototype, each object of the Calendar type will have the readableTime function.


3 ways of creating functions in javascript 2007-03-26

In javascript, all functions are an instance of the class Function (with a capitalized F).

The old way

Everybody knows how to do it. In fact most languages do it this way. Boring but you can't write javascript without knowing it.

[source:javascript] function f() { } [/source]

The uppercase F way

You can directly create an instance of the Function class this way.

[source:javascript] var f = new Function(“alert('Function called');”); f(); [/source]

The problem with that is that the code of the class is passed as a parameter of the constructor. A lot of people use this method to create “dynamic” functions but they do just because they don't know of the lowercase f way of doing it.

[source:javascript] var i = 100; // “dynamically” alert the i variable var alertNumber =new Function(“alert('Number is ” + i + “');”);

alertNumber(); [/source]

It looks bad for such a simple example. It gets uglier as it gets more complex. Please, don't use this method.

The lowercase f way

This one is the one you're looking for. Why? Because it is as handy as the uppercase F but you don't have to write the code as a string. Example, I dynamically load an image and I want to alert when the image is ready.

[source:javascript] var img = new HtmlImage(); img.src=“…”;

var onLoadFunction = function() { alert(“Image is ready!”); }

img.onload = onLoadFunction; [/source]

But wait!

As I was writing this, I realized something that I didn't realize before. The old way of writing functions is not as boring as I thought.

[source:javascript] function parent() { function child() { alert(“Child function called”); }

// Assign the function to a variable
var childFunction = child;

childFunction();

}

parent(); [/source]

Executing above code will alert “Child function called”. So, javascript also creates a variable called child when I write function child() {}. Interesting.


What are javascript prototypes? (longer answer) 2007-03-25

[I've also written the short answer (for advanced javascripters)]

Javascript is using prototypes and is the only language I know that is doing it. What is the idea behind it? Simple. With prototypes, you can extend (add methods/properties) any class you want anywhere you want anytime you want even if you are not the owner of that object. Object-oriented purist will be shocked but I am more than pleased with that.

Why using prototypes?

It's memory-friendly By adding a method to a class prototype, you are creating a single occurence of the function that is referenced by every objects of that type. It's easy To add a method to a class, no need to create a new class. Juste write TheClass.prototype.theMethod = function() {//code here} and it's done.

It's fun! Maybe not as fun as drinking kool-aid but compared to the complexivity of other languages, we have a champ.

How to use prototypes

Simple. Write the [NameOfTheClass].prototype.[NameOfTheExtension].

You want to add a trim function to the String object? (thanks Greg for the correction)

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

You want to add an oldValue property to the string

String.prototype.oldValue = “the old value”;

Beware! All the new String objects and the one already declared will have a property with the value “the old value” inside. I can't think of a particular reason why one would do this. If you have one, please comment.


How to create objects in object-oriented javascript 2007-03-23

[UPDATE : This post is outdated. Check out the new post on how to create objects.]

Javascript is a functional programming language thus having no “real” objects. You can write it the way you want : procedural spag, functional, object or whatever word you know. Why should I write it object-oriented? Because, OO has proven many times its ease of use and great encapsulation. In this paper, I won't talk about why but about how.

There are hundreds of way of writing OO javascript, I tried a lot of the most commons and I finally adopted one : oo using prototypes.

1. Creating an empty class

I like cats so here's a complete example for a cat that meows.

First, I create an empty class.

[source:javascript] function Cat() { } [/source]

Hmmmm… that looks a lot like a function. In fact, it's a function. Why classes are function? Because javascript is a functional language. More on that later (maybe).

2. Creating the constructor

When I have a cat that meows, I want to see its name. I add a name property that is initialized in the constructor of the class.

[source:javascript] function Cat(name) { this.name = name; } [/source]

What is this? This, is a reference on the current instance of the object. By calling this.name = name, we instantiate an public variable for the object that has the value name (the name of the cat).

3. Adding a instance method

As I said earlier, I want the cat to meow. So, I will add a meow() method to the class that will be available to every instance.

[source:javascript] function Cat(name) { this.name = name; }

Cat.prototype.meow = function() { alert(“meow!”); } [/source]

I used the class' prototype. This is one of the hundred ways of adding a method but it's the best way because we create a single reference for all the objects of that class.

4. Using variables of an object

Hey, didn't you read the specs? I said that I wanted to see the name of the meowing cat.

[source:javascript] Cat.prototype.meow = function() { alert(this.name + “ : meow!”); } [/source]

Did you see? I used the this (reference on the current instance of the object). By doing that, I simply call the variable that I defined in my constructor (see point #2).

5. Making the cat meow

Now I'm ready to make the cat meow. On the onload property of the body element, I call a function named bodyOnload.

<html> <body onload='bodyOnLoad();' /> </html>

In the bodyOnLoad function, I create a Cat object and call the meow() method.

[source:javascript] function bodyOnLoad() { var mistigri = new Cat('Mistigri'); mistigri.meow(); } [/source]

I should see an message box with the message “Mistigri : meow!” inside.

In conclusion

Ok, that was an easy one but though it may seem obvious to you, it is not alway as clear for some of my fellows. The important thing I wanted to show was how to create a class method (see point #3). This is the best/safest/fastest way of doing this.


How to do enumerations (enum) in javascript 2007-03-22

One of the most common mistake I see when I use a third-party javascript library is the enormous amount of “constants” that is 152 characters to ensure its uniqueness. Example, a color chooser named KikaColorChooser. If it has a constant for the type of display, it will be named something like KIKACOLORCHOOSERDISPLAYTYPE_SMALL (a constant of 35 characters long). Ugly.

The second most common mistake is to have a short constant name that have dozens of friends with the same name. DISPLAY_SMALL is a good example.

The solution?

[source:javascript]

// The class function KikaColorChooser() { }

// …implementation here…

// The display type KikaColorChooser.displayType = { small : 0, big : 1 }

[/source] Thanks to the power of anonymous objects.

The downside

After writing this article, I remarked that my first argument could not stand.

I had the constant KIKACOLORCHOOSERDISPLAYTYPE_SMALL and the new solution is KikaColorChooser.displayType.small. The old solution is 35 characters long and the new one, 34. And no you can't shorten the new solution in the class by just writing this.displayType.small.

Still, you should do it just for the cleanliness of your code and to impress your friends.