Prototyping and Inheritance in Javascript

A prototype in Javascript is exactly what it sounds like: a prototype for object to follow.  The best way to explain it would be with an example, of course! We’ll throw in some inheritance while we’re at it.

Let’s say we have an an Animal object, that has a name and numLegs, which is a characteristic all animals will have (yes, I realize not all animals have legs, it’s just an example :D ):

function Animal(name, numLegs) {
  this.name = name;
  this.numLegs = numLegs;
};

Now let’s create a function (method) for that object’s prototype:

Animal.prototype.sayName = function() {
   console.log("Hi my name is " + this.name);
};

This means that any object that uses the animal prototype (or blueprint) will have access to the functions and properties.

Now we need to create something that will inherit from Animal, therefore, any type of animal:

function Dog(name){
  this.name = name;
  this.numLegs = 4;
};

This is where inheritance kicks in now. First of all, you must set the inheritance like such:

Dog.protoype = new Animal();

Now if we create an instance of Dog, who is inheriting from Animal:

var nicky = new Dog("Nicky");

We can now use the methods that were defined within the Animal prototype:

nicky.sayName();

Inheritance works like a chain. There’s many different types of dogs, but it would be useless to make an object of each of them instead of just “Dog”, since they all share properties (ex. number of legs) and methods (sayName()). So instead, we make a “Dog” object that can have other objects that need even more specific things (maybe a “bark” method, that all dog do [unless you're in La Jolla! :( ]).

So if we create a Labrador object:

function Labrador (name) {
  this.name = name;
};

and make it inherit from Dog, by setting the prototype:

Labrador.prototype = new Dog();

Then once we make a new instance of that Labrador:

var brownie = new Labrador();

So now our brownie object will have access to both Animal and Dog’s methods/functions and properties, apart from it’s own!:

brownie.name; // this will be "Nicky", as defined in the Labrador instance creation
brownie.numLegs; // this will be 4, as inherited from Dog
brownie.sayName(); // this will be "Hi, my name is Brownie", as inherited from Animal.
Ideally, if you're creating a Labrador object by itself, it would do different things than other dogs, otherwise it's just easier to define a "breed" property in Dog and just mention it there. This is just an example to show how it works, but before defining objects, it's a good ideal to model everything so you don't have too many (or too few) objects. 

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>