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
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.
/* The constructor of the Mammal class */
  function Mammal() {
  }

/* The constructor of the Cat class / function Cat() { } // The magic that inherits Cat from Mammal is here!!!!! 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!
/ Above code goes here */

// Create a cat var theCat = new Cat();

// Check if the cat is an instance of the Cat class if (theCat instanceof Cat) { alert("theCat is an instance of the Cat class"); }

// Check if the cat is an instance of the Mammal class if (theCat instanceof Mammal) { alert("theCat is an instance of the Mammal class"); }

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