Why does the “Cat.prototype = new Mammal()” line below not work inside the Cat() function, but it works outside the Cat() function?
function Mammal() {
Mammal.prototype.hasHair = function() { return true; }
}
alert( new Mammal().hasHair() ); // dispays true here
function Cat() {
Cat.prototype = new Mammal();
}
try {
new Cat().hasHair(); // doesn't work. why?
} catch ( err ) {
alert('error'); // displays error here
}
Cat.prototype = new Mammal(); // same line as inside Cat() function
alert( new Cat().hasHair() ); // now it works
I tried this with several different javascript implementations, so I doubt it is an implementation idiosyncrasy. I wonder about this mostly out of curiousity, but also just for organization, I would like to define about Cats inside Cat’s function, not spread out all over everywhere.
Because
prototypemembers are passed to the object instance before constructor is executed.http://jsfiddle.net/vSDbB/
So the code above will work, but if you commented first
new Cat();line it wouldn’t since on thenew Cat().hasHair()line Cat’s prototype doesn’t havehasHair()method