为什么下面的“Cat.prototype = new Mammal()”行在 Cat() 函数内部不起作用,但在 Cat() 函数外部起作用?
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
我尝试了几种不同的 javascript 实现,所以我怀疑它是一种实现特性。我想知道这主要是出于好奇,但也只是为了组织,我想在 Cat 的函数中定义 Cats,而不是到处传播。