Create objects in object-oriented javascript

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.



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.

0 comments: