6

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?

Oriol
  • 274,082
  • 63
  • 437
  • 513
  • 1
    i is an object, and the console tries to show elements as they actually are. Alert can't display objects, so it'll call the toString function. Debugging would be more difficult if objects were always converted to strings on the console. – temporalslide Sep 03 '12 at 21:14

1 Answers1

4

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.

Jon Hanna
  • 110,372
  • 10
  • 146
  • 251