I'm very confused with JavaScript methods defined in objects and the this
keyword.
In the below example, the toString()
method is invoked when Mammal
object instantiated:
function Mammal(name){
this.name=name;
this.toString = function(){
return '[Mammal "'+this.name+'"]';
}
}
var someAnimal = new Mammal('Mr. Biggles');
alert('someAnimal is '+someAnimal);
Despite the fact that the toString()
method is not invoked on the object someAnimal
like this:
alert('someAnimal is '+someAnimal.toString());
It still returns 'someAnimal is [Mammal "Mr. Biggles"]'
. That doesn't make sense to me because the toString()
function is not being called anywhere.
Then to add even more confusion, if I change the toString()
method to a method I make up such as random()
:
function Mammal(name){
this.name=name;
this.random = function(){
return Math.floor(Math.random() * 15);
}
}
var someAnimal = new Mammal('Mr. Biggles');
alert(someAnimal);
It completely ignores the random
method (despite the fact that it is defined the same way was the toString()
method was) and returns: [object object]
Another issue I'm having trouble understanding with inheritance is the value of this
. For example, in the below example
function person(w,h){
width.width = w;
width.height = h;
}
function man(w,h,s) {
person.call(this, w, h);
this.sex = s;
}
this
keyword is being sent to the person object clearly. However, does this
refer to the subclass man
or the superclass person
when the person object receives it?
Thanks for clearing up any of the confusion I have with inheritance and object literals in JavaScript.