constructor function's object literal returns toString() method but no other method

Posted by JohnMerlino on Stack Overflow See other posts from Stack Overflow or by JohnMerlino
Published on 2010-06-12T21:56:55Z Indexed on 2010/06/12 22:03 UTC
Read the original article Hit count: 313

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 send to the person object clearly. However, does "this" refer to the subclass (man) or the super class (person) when the person object receives it?

Thanks for clearing up any of the confusion I have with inheritance and object literals in javascript.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about inheritance