Codemash 2013 – Understanding Prototypical Inheritance

presenter Guy Royse, Piller Technologies, pillartechnology.com.

9: 45 AM 1/10/2013 Salon D

This was a very solid overview of prototypical inheritance in Javascript.  The presentation was energetic and delivered exactly what it intended to delivery, a explanation and overview of prototypes in the Javascript language.

I was mystified initially as to how this worked, but it turns out to be fairly straightforward.  An object in Javascript is just a collection key value pairs.   Keys in this collection can refer to values that are functions to objects can have behavior.  Javascript is dynamic so when you call a method on an object you don’t know if it is there or not when you call it.  If the function exists on that object it will be called, if not the object as a prototypical parent, and it will pass the call to it to see if that parent has what you are looking for.  If the parent has what you are looking for it is returned, if not it looks to it’s parent.  The top of this prototypical chain is the Object.

Where it gets confusing is that objects have a constructor function and it is on this function that the prototype is stored.  When you create an object using hte new keyword in Javascript the constructor function executes and the object that exists in the .prototype property of the constructor function is set as the prototypical parent of the new object instance.  In this way every instance created of an object will have to same prototypical parent reference.

To set a parent on an object that is dynamically created you have to create a constructor function for the object, set it’s prototype to the parent the new object should have, and then execute the constructor through the new keyword to get an instance.

The above structure means you can add behavior to prototypes by acting on the prototype property of an objects constructor function.  This allows us to add behavior to any object in javascript.  For instance if I want to add a method to the string object to put append “Bob” to the end of any string I can add the method to the object set in the string’s constructor functions prototype property.  The ‘class’ in javascript is really the constructor function, so I just write String.prototype.AddBob(); and now all strings have the AddBob() function!

 

Leave a Reply

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