Class Inheritance in Javascript


My previous post showed how to create classes in Javascript. This addendum post shows how to create an inherited class from a parent class.

The concept is simple.

  1. Declare and define your parent class
  2. Declare and define your child class without defining the parent-child relationship
  3. Add a new instance of your parent class to your child class' prototype. Now the child class has access to the parent class' properties and methods. This last step may seem counter-intuitive, but the example below helps to clarify what I mean.
JAVASCRIPT:
  1. function SuperHero(heroID, p1, p2, p3) {
  2.     ...
  3.     ...
  4.     ...
  5. }
  6.  
  7. /* Do some extending of SuperHero's prototype here */
  8.  
  9. //Now let's define our child class - note that we do not initially define the parent-child relationship
  10. function AlienSuperHero(heroID, homePlanet, race, p1, p2, p3) {
  11.     ...
  12.     //Now we indicate the parent-child relationship
  13.     this.prototype = new SuperHero(heroID, p1, p2, p3);
  14. }
  15.  
  16. /* Do some extending of AlienSuperHero's prototype here */

Usage would be along the lines of:

JAVASCRIPT:
  1. var MartianManhunter = new AlienSuperHero(3454, 'Mars', 'Martian', 'Flight', 'Telepathy', 'Shapeshifting');
  2. if (fire) {
  3.     //This is a method defined in the parent class
  4.     MartianManhunter.losePowers();
  5. }

  1. No comments yet.
(will not be published)