At some point in time, when trying to mimic classical inheritance in JavaScript and the call to super(), I did doing something stupid like this:

function Animal(name, age) {  
        this.name = name;
        this.age = age;
}

function Dog(name, age, color) {  
        this.color = color;
        Dog.prototype = new Animal(name, age);
}

var d1 = new Dog('king', 10, 'red');

console.log(d1.name); // undefined  
console.log(d1.age); // undefined  
console.log(d1.color); // red  

I was then surprised that it did not worked as i expected... After all, i was setting the prototype property of my constructor function to my newly created Animal object!

Setting Dog's prototype outside the constructor function would obviously work, but then i would not have access to the arguments to pass on to the Animal constructor as i wanted..

The problem reveals itself if you create a new Dog:

var d2 = new Dog('comet', 8, 'blue');

console.log(d2.name); // king  
console.log(d2.age); // 10  
console.log(d2.color); // blue  

By understanding that javascript new operator first set's up the prototype of the newly created object and only after it actually executes the constructor function everything becomes clear!

To be precise, this is the order of events upon executing new Dog() :

  1. a new object is created
  2. the constructor property of the new object is set to Dog
  3. the new object will delegate to (inherit from) Dog.prototype
  4. The Dog() constructor function is called in the context of the new object

Also of note is the fact that constructor property set in 2 is not an ordinary javascript property. It is used by the instanceof operator, which tests whether an object has in its prototype chain the prototype property of a constructor. It won’t show up if you enumerate the properties of the object and if we try to set it, we’ll end up setting a normal property on top of this special one.

We can also use the __proto__ special property to validate the prototype of a specific object, which is set in 3.