I’ve been playing around with prototypal inheritance in JavaScript and have been confused by the behavior of the new keyword. I cannot understand why the [[prototype]] property of the inheriting object points to Function.prototype and not the prototype of the inherited object. Consider 2 constructor functions (below):
function Animal(name) {
this.name = name;
}
function Cat(name) {
Animal.call(this, name);
}
Cat.prototype = new Animal();
Querying the prototype of the constructor function Cat, I get some interesting results:
Cat.__proto__ === Animal.prototype; //returns false -- shouldn't this be true?
Cat.__proto__ === Function.prototype; //returns true
Cat.prototype instanceof Animal; //returns true, as expected
My understanding was that the [[prototype]] of Cat should be updated to point to Animal.prototype when we set it’s prototype property to a new instance of Animal, which should in essence
- create a new object based on
Animal.prototypeand - internally set
Cat.[[prototype]]toAnimal‘s external prototype property?
I’ve tried this in both Chrome and FF with the same result. What gives?
Also, when we assign Cat.prototype to a new Animal(), what should Cat.prototype be? i.e.:
//if Cat.prototype = new Animal();
//then
Cat.prototype === Animal.prototype; //get false. Should this be true?
The
Catconstructor is a function. Therefore, it inherits fromFunction.prototypewhich in turn inherits fromObject.prototype. This is also true for theAnimalconstructor and all other function objects.Just because you assigned to
Cat.prototypedoesn’t change the inheritance link of theCatconstructor itself (inheritance links are immutable anyway).Note that
Catinstances don’t inherit fromCat, but fromCat.prototype. So, you don’t care about the prototype link of theCatconstructor anyway.