In the below code, the alert message returns in one instance: 'someAnimal is [Mammal "Mr. Biggles"]'
I don't understand how this is possible. We pass as an argument 'Mr. Biggles' to the Mammal constructor. Then assign it to the object name property. But then it ends there. There is a function called toString which will return the alert. But the toString function is not being called like this:
alert('someAnimal is '+someAnimal.toString());
If it was like how it is above, it would make sense to me but now it makes no sense to me because I don't see where that toString() is being called - I only see that it is prototyped to the Mammal object.
Any help explaining this will be greatly appreciated.
Code:function Mammal(name){ this.name=name; this.offspring=[]; } Mammal.prototype.haveABaby=function(){ var newBaby=new Mammal("Baby "+this.name); this.offspring.push(newBaby); return newBaby; } Mammal.prototype.toString=function(){ return '[Mammal "'+this.name+'"]'; } Cat.prototype = new Mammal(); // Here's where the inheritance occurs Cat.prototype.constructor=Cat; // Otherwise instances of Cat would have a constructor of Mammal function Cat(name){ this.name=name; } Cat.prototype.toString=function(){ return '[Cat "'+this.name+'"]'; } var someAnimal = new Mammal('Mr. Biggles'); var myPet = new Cat('Felix'); alert('someAnimal is '+someAnimal); // results in 'someAnimal is [Mammal "Mr. Biggles"]' alert('myPet is '+myPet); // results in 'myPet is [Cat "Felix"]' myPet.haveABaby(); // calls a method inherited from Mammal alert(myPet.offspring.length); // shows that the cat has one baby now alert(myPet.offspring[0]); // results in '[Mammal "Baby Felix"]'


Reply With Quote

Bookmarks