Prototypal vs. Functional Inheritance in JavaScript

If you ever found JavaScript’s prototypal inheritance confusing, do yourself a favor and open this article, open a JavaScript console and code each example in the article. You will definitely come away with a better understanding of how prototypal inheritance works in JavaScript.

After reading the article, I thought a good exercise would be to compare CoffeeScript class definitions vs. the prototypal inheritance style those definitions generate vs. Douglas Crockford’s functional inheritance style outlined in his book JavaScript: The Good Parts.

CoffeeScript Class Definitions

The CoffeeScript homepage gives the following example to demonstrate CoffeeScript’s class syntax:

class Animal
  constructor: (@name) ->

  move: (meters) ->
    alert @name + " moved #{meters}m."

class Snake extends Animal
  move: ->
    alert "Slithering..."
    super 5

sam = new Snake "Sammy the Python"

See at

Anyone experienced with class-based inheritance should have little trouble understanding this code.

Prototypal Inheritance 

The JavaScript generated by the CoffeeScript compiler uses prototypal inheritance. The compiler first generates a utility function that sets the properties on the child constructor and then sets up the prototype chain. It also creates a convenient super property that allows an object to call methods on its prototype.

__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) 
   for (var key in parent) 
      if (, key)) 
         child[key] = parent[key]; 

   function ctor() 
      this.constructor = child; 
   ctor.prototype = parent.prototype; 
   child.prototype = new ctor(); 
   child.__super__ = parent.prototype; 
   return child; 

See at

The constructor functions are then generated as follows:

Animal = (function() 
   function Animal(name) 
   { = name;

   Animal.prototype.move = function(meters) 
      return alert( + (" moved " + meters + "m."));
   return Animal;

Snake = (function(_super) 
   __extends(Snake, _super);
   function Snake() 
      return Snake.__super__.constructor.apply(this, arguments);

   Snake.prototype.move = function() 
      return, 5);
   return Snake;

sam = new Snake("Sammy the Python");

See at

Notice how easily the Snake constructor can access its Animal prototype using the super property.

Functional Inheritance

In JavaScript: The Good Parts, Crockford advocates a functional inheritance style. Converting the original CoffeeScript code to this style results in the following:

Function.prototype.method = function(name, func)
   if (!this.prototype[name])
      this.prototype[name] = func;
      return this;

Object.method('superior', function(name)
   var that = this;
   var method = that[name];
   return function()
      return method.apply(that, arguments);

var Animal = function(spec)
   var that = {}; =;

   that.move = function(meters)
      alert( + ' moved ' + meters + 'm.');
   return that;

var Snake = function(spec)
   var that = Animal(spec);
   var super_move = that.superior('move');

   that.move = function()
   return that;

sam = new Snake({name:'Sammy the Python'});

See at

The functional style does nothing with prototypes. Inheritance is implemented by creating an object from a base function, similar to a constructor, but without the need for the new operator. Access to super methods is accomplished by extending the built-in Object and Function objects. Notice that any child object wanting access to a super method must create a new function pointing to the super method.

Which One?

So which method is better? Because I’m more familiar with class-based inheritance, I’d rather just use CoffeeScript and ignore the underlying JavaScript implementation altogether. I like the fact that I can look at a CoffeeScript class definition and see on a single line both the name of the "class" and the name of the "class" it extends. In both JavaScript implementations, I have to search other lines to find the object that my object is extending. I find the use of the super property a much more elegant solution when it comes to super methods. The functional method for accessing super methods would not scale well if there are a large number of super methods you want to access.

Even if you decide to work at the CoffeeScript level, it’s imperative that you understand the JavaScript it compiles into. Again, read the article referenced above and the generated JavaScript becomes trivial to understand.

Finally, if you want a much more thorough comparison and richer examples of prototypal vs. functional inheritance styles, this article provides both and makes a very strong case for the use of prototypal inheritance.

Turn Your Mac into a Thermometer with Arduino

The topic of the Arduino came up around A&L’s “virtual water cooler” last week. About a year and a half ago, I purchased a SparkFun Inventor’s Kit for Arduino. The kit is a fun way for a hardware novice like me to get started and learn some basics. It comes with more than a dozen sample projects such as lighting LEDs, spinning a motor and generating audio.

Inspired by the discussion at A&L, I pulled my kit out this past weekend and put together the sample circuit that reads temperature. In addition to learning hardware, another ulterior motive in my Arduino purchase was to get my son interested in electronics. He’s still a little young to really understand everything and instead likes to pretend the breadboard is a train. It makes it a little hard to put the circuit together as the “circuit train” travels around the tracks. But he does enjoy seeing the end result and playing with the circuits we make.

Because the sample temperature project just prints numbers to a console window, I thought I’d spruce it up for my son a little bit and write a UI that simulated a thermometer. I found some Java code on an Arduino Playground page that reads the temperature measurements written to the serial port by the Arduino board. Getting everything in place was just a matter of wiring up the SparkFun schematic, integrating the Java code and writing a little thermometer widget. All of the resources needed for this project can be found here.

I finished everything up late last evening so my son has yet to see the end result. Something tells me he would be more impressed if I animated steam coming out of a train engine to represent the temperature.

There was a recent TED talk by one of the creators of Arduino. It’s fascinating to see the types of projects people are completing with the Arduino. I think we’re in for a fascinating future.

Fun with CoffeeScript and Backbone.js : Part 3

Part 1 of this series can be read here.

Part 2 of this series can be read here.

The project is a simplified morse code simulator that animates morse code being sent over a telegraph line. The complete source is available here and the running code can be seen here.

In this post I’ll discuss my thoughts on CoffeeScript and Backbone.js.

JavaScript has slowly become my favorite programming language as I’ve done more web development. As you learn its Good Parts, you start to realize how powerful of a language it is. I’ll never forget the Aha! moment I had when I wrote my first closure.

CoffeeScript takes a great language and makes it even better. It hides the bad parts of JavaScript and adds the expressiveness of Ruby and Python. The addition of classes shields the developer from JavaScript’s prototypal inheritance and is much easier to understand for developers used to class-based inheritance. Admittedly, this was a small demo, but tracking runtime errors in the JavaScript code back to the CoffeeScript code was trivial. I definitely plan to use CoffeeScript as much as possible in future projects.

This demo only scratched the surface of Backbone.js. Views can be initialized with templates, making complex models easier to render. Backbone.js also provides functionality to automatically synch your objects to/from a server, provides support for collections and also provides routing functionality to ensure the back button works in single-page applications. I’m very interested in learning more about Backbone.js and using it to reduce the amount of front-end code I need to write.

In general, I think the combination of CoffeeScript and Backbone.js results in a much cleaner application. View code is segregated from the model code and developers are forced into keeping things more modular. This style would also make unit testing easier. I’m anxious to continue experimenting with both of these technologies to see how they boost my productivity and allow me to develop larger web-apps in a more controlled manner.

Fun with CoffeeScript and Backbone.js : Part 2

Part 1 of this series can be read here.

The project is a simplified morse code simulator that animates morse code being sent over a telegraph line. The complete source is available here and the running code can be seen here.

In this post I’ll discuss the code that handles updating the UI.

Communication Line View

The CommunicationLineView class is a Backbone.js view class that handles the animation of signals sent across the communication line. In Part 1, I mentioned that the model representing the communication line fires a hasNewData event each time the tokens progress one step through the line. As you can see above, this view is bound to that event and rerenders itself every time it receives the event. The render method iterates over the current tokens and draws the appropriate token shape for each line position.

Decoder Model

The Decoder model is responsible for determining what characters the user has sent across the line. The processToken function is called each time the tokens on the communication line progress one step through the line. The decoder processes the current tokens sent by the user anytime it sees 10 or more empty tokens in a row or receives a word-break token. If the decoder parses a known morse code sequence it fires a parsedCharacter event letting the message field know it needs to rerender itself.

Decoder View

The Decoder view is a Backbone.js view class that represents a simple text box to display the characters the user has sent across the line. Anytime the Decoder model emits a parsedCharacter event, the Decoder view appends the parsed character to the end of its text box.

Fun with CoffeeScript and Backbone.js : Part 1

CoffeeScript has been all the rage lately and I’ve been wanting to hop on board the bandwagon. I’ve also seen Backbone.js mentioned quite a bit and was even more intrigued after listening to this .NET Rocks podcast. I decided to convert some plain JavaScript code I had in a side project to use both CoffeeScript and Backbone.js and see how things went.

The project is a simplified morse code simulator that animates morse code being sent over a telegraph line. The complete source is available here and the running code can be seen here.

In this post I’ll discuss the code that handles the user input.


The init function sets up all of the Backbone.js model/view classes. Note that each Backbone view is initialized with both its corresponding HTML element and corresponding model object.

The init function also draws the “communication line” in a canvas element.

Input View

The application processes user input using the StraighKeyInput class, a Backbone view class associated with an input button:

The class uses two timers to determine which “token” a user intends to send across the line. Using Backbone’s declarative style for event binding, I bind the mousedown event to a function that starts both timers. The mouseup event is bound to a function that pushes the appropriate token to the model based on how long the user held down the input button.

Input Model

The CommunicationLine class is a Backbone model class that represents the tokens currently moving across the telegraph line. It also contains a queue that holds the input tokens generated by the user. The class also holds a reference to the object responsible for decoding the user input (more on that tomorrow).

Every 100 milliseconds, the communication line shifts its tokens over one spot. The token popped off the line is passed to the decoder. The model then checks the input queue to determine if a user-generated token is available to be pushed onto the line. If not, the model pushes a default token (an empty string). The model then triggers an event to indicate the communication line state has changed and that the object representing the communication line view needs to be re-rendered (more on that tomorrow).