Oriol
Oriol

Reputation: 288250

Why the console doesn't use entered object's `toString` method?

If I open the console and enter...

var f=function(a){
    this.toString=function(){
        return "-->"+a;
    }
},i=new f(5);
i;

...it returns ({toString:(function () {return "-->" + a;})}).

But if I enter...

var f=function(a){
    this.toString=function(){
        return "-->"+a;
    }
},i=new f(5);
alert(i);

...it alerts "-->5"

It doesn't matter me very much, but I would prefer the first code to return "-->5". Is there a way to do that, or is it intentional that the console doesn't use toString?

Upvotes: 6

Views: 1082

Answers (1)

Jon Hanna
Jon Hanna

Reputation: 113282

It's intended for debugging use, so telling you all there is to say on an object is likely to be useful.

After all, if you'd wanted the result of calling toString() you would have asked it, with i.toString() or "" + i, but if that was the default behaviour there wouldn't be a way to get the deeper representation you do get.

Upvotes: 4

Related Questions