Javascript’s Prototype-Based Inheritance

Let’s create a Dragon “class” in Javascript that we can use to inherit from.

var Dragon = function(color) {
  this.color = color;

// prototype is a special object used for inheritance in Javascript.
// We could have added the attack method as a member variable similar to color, however we'll use it on the prototype
// later.
Dragon.prototype.attack = function() {
  console.log("The " + this.color + " dragon breathes fire!");

var dragon = new Dragon("red");
dragon.attack();  // The red dragon breathes fire!

Calling “new Dragon();” creates a new object that inherits anything set on the Dragon.prototype object. First, Javascript will check to see if a property exists on Dragon itself. If it doesn’t exist on Dragon, it will check Dragon.prototype. We can check to see whether properties exist on Dragon or it’s prototype as follows:

dragon.hasOwnProperty("color"); // true
dragon.hasOwnProperty("attack"); // false, this is not an "own" property - it's part of the prototype

The hasOwnProperty method differentiates between an objects properties and those that were inherited from it’s prototype. Where does the “hasOwnProperty” method come from? The hasOwnProperty method comes from Object.prototype:

1) dragon inherits from Dragon.prototype
2) Dragon.prototype inherits from Object.prototype
3) Object.prototype inherits from “null” prototype – essentially, null allows is the dead-end in our prototype chain

Let’s try some inheritance out: = function() { console.log("The " + this.color + " dragon flaps its wings and flies!"); }; // The red dragon flaps its wings and flies!

// Now lets create a Baby Dragon

var BabyDragon = function(color) {, color); // Essentially super().  Set color, but on BabyDragon, not Dragon. = function() { console.log("The " + this.color + " dragon tries to fly, but is still too young!"); }

// We need to set the BabyDragon prototype to inherit from the Dragon prototype.  This will give us access to the attack method.
BabyDragon.prototype = Object.create(Dragon.prototype);

// Set this, otherwise it will be Dragon
BabyDragon.prototype.constructor = BabyDragon;

var baby = new BabyDragon("green");; // The green dragon tries to fly, but is still too young!
baby.attack(); // The green dragon breathes fire!

ECMAScript 2015 (6th Edition) introduces the class keyword to Javascript which adds some interesting syntatic sugar for you to explore.

Leave a Reply

Your email address will not be published. Required fields are marked *