Lets face it JavaScript inheritance patterns are a bit mind boggling. Especially pseudo classical inheritance. So lets start at the top and get a couple of things straight.

  • Objects are collections of name/value pairs
  • Objects are create from the Object constructor
  • Objects have a hidden "link" to another object, the prototype object (Object.prototype).
  • Functions are created from the Function constructor, and are linked to Function.prototype
  • Function.prototype is linked to Object.prototype because functions are objects in JavaScript

Phew. So we can see there are a lot of relationship lines all over the shop - a bit like the royal family.

Anyhow, lets take a look at how pseudo classical inheritance works. So just like breakfast, let's start with an egg.

var Egg = function() {  
  this.age = 0;
  this.color = "blue";
  this.food = "albumen";

Now we want Birds to inherit from Eggs. How do we do this?

var Bird = function() {  
  this.age = 2;
  this.color = "grey";
  this.job = "grow some feathers";

Bird.prototype = new Egg(); //or Object.create(Egg.prototype);  
Bird.prototype.constructor = Bird;  

Wow, that is a lot of code just to inherit. Here is what is going on.

The Bird constructor function calls the Egg constructor using Egg.call(this); which adds properties from Egg to Bird, as we have passed the parameter "this" to be bound to "Bird".

Now the constructor will be referencing Egg as we have just inherited the prototype from "Egg". Because of this we need to fix the correct constructor reference by Bird.prototype.constructor = Bird;

Make sense?

Have a fiddle

Just as an aside, it is interesting to know that you can create a function using new, and the last argument is the function body:

> new Function('test', 'return console.log(test)')('Hi there');
> Hi there


Ecma 5.1