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.
- Declare and define your parent class
- Declare and define your child class without defining the parent-child relationship
- 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:
-
function SuperHero(heroID, p1, p2, p3) {
-
...
-
...
-
...
-
}
-
-
/* Do some extending of SuperHero's prototype here */
-
-
//Now let's define our child class - note that we do not initially define the parent-child relationship
-
function AlienSuperHero(heroID, homePlanet, race, p1, p2, p3) {
-
...
-
//Now we indicate the parent-child relationship
-
this.prototype = new SuperHero(heroID, p1, p2, p3);
-
}
-
-
/* Do some extending of AlienSuperHero's prototype here */
Usage would be along the lines of:
JAVASCRIPT:
-
var MartianManhunter = new AlienSuperHero(3454, 'Mars', 'Martian', 'Flight', 'Telepathy', 'Shapeshifting');
-
if (fire) {
-
//This is a method defined in the parent class
-
MartianManhunter.losePowers();
-
}