вторник, 7 сентября 2010 г.

How to inherit classes in javascript

http://www.javascriptkata.com/2007/05/22/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.

Комментариев нет:

Отправить комментарий