Archive for the ‘prototype’ Category.

How to inherit classes in javascript

First of all, since I made the front page of Ajaxian, a lot of new readers joined in. Welcome to all of you. I would also take a moment to explain that Javascript Kata is a technical blog about javascript and though I will talk here and there about ajax, it is not focused on that subject. It is more about the good javascript techniques that should come along with all the ajax you have to do. I update this site 2 or 3 times a week. Keep reading!

There are hundreds of ways to do inheritance in javascript but a single one is simpler, cleanier and prettier than all the other ones.

Note!
Before reading this article, you should take a look at
How to create objects in object-oriented javascript.

A one-liner

To inherit a class in javascript, it’s a one-liner

  1. TheSubClass.prototype = new TheParentClass();

As simple as that!

Where to write the one-liner

The problem with that one-liner is where should it goes? Once again, the answer is simple : after the constructor of the sub-class. It may look strange but it is extremely effective.

  1. /* The constructor of the Mammal class */
  2. function Mammal() {
  3. }
  4.  
  5. /* The constructor of the Cat class */
  6. function Cat() {
  7. }
  8. // The magic that inherits Cat from Mammal is here!!!!!
  9. Cat.prototype = new Mammal();

Is this true inheritance?

In the hundreds of other ways of inheriting classes in javascript, I think that this is the only one that is a true inheritance. What do I mean by true inheritance? I mean that javascript recognizes it as a sub-class of the class. Check this out!

  1. /* Above code goes here */
  2.  
  3. // Create a cat
  4. var theCat = new Cat();
  5.  
  6. // Check if the cat is an instance of the Cat class
  7. if (theCat instanceof Cat) {
  8.     alert("theCat is an instance of the Cat class");
  9. }
  10.  
  11. // Check if the cat is an instance of the Mammal class
  12. if (theCat instanceof Mammal) {
  13.     alert("theCat is an instance of the Mammal class");
  14. }

If you execute this code, you’ll see that the cat is an instance of the Cat class and the Mammal class.

What are javascript prototypes? (longer answer)

[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

[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 extend javascript classes

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.

[source:javascript]

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

[/source]

Easy.

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)

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