understanding calling a function with prototype property
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.
var newBaby=new Mammal("Baby "+this.name);
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
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); // results in '[Mammal "Baby Felix"]'
The Object() object has a built-in toString() function. You are overriding it with yours.
alert always converts its argument to a string-
strings are all it knows. It starts at the object and climbs up
the prototype chain until it hits one that defines the toString method to use.
Just remember that in most other expressions, mypet.offspring will refer to the the actual object, and not its string.
Users Browsing this Thread
There are currently 1 users browsing this thread. (0 members and 1 guests)
Tags for this Thread