Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 540
Oriol Avatar asked Sep 03 '12 21:09

Oriol


1 Answers

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.

like image 59
Jon Hanna Avatar answered Sep 18 '22 11:09

Jon Hanna