INHERIT classes in javascript

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

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. /* The constructor of the Cat class */
  5. function Cat() {
  6. }
  7. // The magic that inherits Cat from Mammal is here!!!!!
  8. 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. // Create a cat
  3. var theCat = new Cat();
  4. // Check if the cat is an instance of the Cat class
  5. if (theCat instanceof Cat) {
  6.     alert("theCat is an instance of the Cat class");
  7. }
  8. // Check if the cat is an instance of the Mammal class
  9. if (theCat instanceof Mammal) {
  10.     alert("theCat is an instance of the Mammal class");
  11. }
If you execute this code, you’ll see that the cat is an instance of the Cat class and the Mammal class.

0 comments: