Tag Archives: JavaScript

JavaScript Prototypes for the Object Oriented Developer

I interview plenty of Web Developers who list JavaScript (not just JQuery) as a technical skill.  But when I ask them what a prototype is in JavaScript they give me blank stares.  This would be like a candidate coming in for an Object Oriented interview (C++ / Java / C#) and not knowing what inheritance is.

So in the interest of getting future job candidates prepared for one of my interview questions before coming through my door, I will demonstrate JavaScript prototypes with an example:

function parent() {};

var child1 = new parent();

// this line will throw an exception as there is no function called namemyparent()
child1.namemyparent();

// now lets create the function on the parent
function adam() { return "Adam"; }
parent.prototype.namemyparent = adam;

// lets try this again -- now returns "Adam" -- the child dynamically inherited a new method from the parent
child1.namemyparent();

// unlike object oriented languages (such as C#) we can change the parent anytime
function ilene() {return "Ilene"};
parent.prototype.namemyparent = ilene;

// check this out -- child now returns "Ilene"
child1.namemyparent();

In other words, a prototype allows you to extend a JavaScript object with methods or properties.  They are kind of like a dynamic language version of C# extension methods.  (Of course prototypes came long before C# extension methods.  Prototypes where added to JavaScript in 1996.  The first version of C# came in 2002 and the first version with extension methods came in 2007.  Also prototypes support properties, not just methods.)

I like to think of prototypes more like object oriented inheritance.  But there is at least one major exception.  Once a parent class is defined in an object oriented language it cannot be changed.  This restriction is likely what caused Microsoft to have to introduce extension methods to support new concepts like LINQ.  As I demonstrated, the ‘parent’ may change at any time in JavaScript.

Of course prototypes allow me to do all the fun things I can do with inheritance in object oriented languages, including replicating the concept of polymorphism. There is even a JavaScript operator to verify whether a child belongs to a parent: instanceof.