[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.

comments powered by Disqus