Example 2 : JavaScript Classical Inheritance diagram

This is an example from Kenneth, also about creating object by constructor but we are focus on the issue of prototype chain during those series of objects and instances. Prototype objects are also just simple objects and may have their own prototypes. If a prototype has a non-null reference to its prototype, and so on, this is called the prototype chain (by Dmitry).

The following is a chart of JavaScript Pseudo Classical Inheritance. The constructor Foo is just a class name for an imaginary class. The foo object is an instance of Foo.

And now we can see from the diagram why when we inherit Dog from Animal, we would do:

function Dog() {} // the usual constructor function

Dog.prototype = new Animal();

Dog.prototype.constructor = Dog;

What happens when new( ) an instance:

Note that the prototype in Foo.prototype is not to form a prototype chain. Foo.prototype points to some where in a prototype chain, but this prototype property of Foo is not to form the prototype chain. What constitute a prototype chain are the __proto__ pointing up the chain, and the objects pointed to by __proto__, such as going from foo.__proto__, going up to foo.__proto__.__proto__, and so forth, until null is reached.

Relation of __proto__ and prototype

JavaScript’s Pseudo Classical Inheritance works like this way: I am a constructor, and I am just a function, and I hold a prototype reference, and whenever foo = new Foo() is called, I will let foo.__proto__ point to my prototype object. So Foo.prototype and obj.__proto__ are two different concepts. Foo.prototype indicates that, when an object of Foois created, this is the point where the prototype chain of the new object should point to — that is, foo.__proto__ should point to where Foo.prototype is pointing at.

What if a function is needed to add

If woofie the object doesn’t have the move method, it will go up the prototype chain, just like any prototypal inheritance scenario, first to the object pointed to by woofie.__proto__, which is the same as the object that Dog.prototype refers to. If the method move is not a property of that object (meaning that the Dog class doesn’t have a method move), go up one level in the prototype chain, which is woofie.__proto__.__proto__, or the same as Animal.prototype.

Animal.prototype.move = function() { ... };