views:

47

answers:

2

I'm thinking in particular of Chrome, though Firebug would be interesting to. I've tried toString() and valueOf(), but neither of those seem to be used. Interestingly, if I take a function it'll display the function definition - but then if I add a toString() method it will show null!

var a = function(){};
console.log(a); // output: function (){}
a.toString = function(){ return 'a'; };
console.log(a); // output: null
a.valueOf = function(){ return 'v'; };
console.log(a); // output: null

Any ideas?

+1  A: 

There's no way I know of. Your best bet will be to define a toString() method on the object you want to log and then call it, either directly or indirectly:

var o = {};
o.toString = function() {
    return "Three blind mice";
};

console.log("" + o);
console.log(o.toString());

Shameless plug: the forthcoming version 1.5 of log4javascript will have Renderers to do this, similar to those found in log4j.

Tim Down
A: 

You should get a better result from Firebug, you should get

var a = function(){}; console.log(a); // output: function a.toString = function(){ return 'a'; }; console.log(a); // output: function, {toString()} a.valueOf = function(){ return 'v'; }; console.log(a); // output: function, {toString(), valueOf()}

http://code.google.com/p/fbug/issues/detail?id=3117

johnjbarton
I have to admit, I had actually not tried it in Firebug (I was a die-hard Firebug user, but I'm on on a Mac and Chrome feels just slightly less out of place than Firefox, so what with the built-in console being available in Chrome I've been kind of just using that recently). I get "function()" as output on Firebug, which is at least less *puzzling* than the Chrome behavior of "setting toString() changes display, but not to the output of toString(), HAHAHA!" And besides, it's not exactly a common use-case. A Function with attributes added? I'm a weirdo.
agnoster
me too ;-)and here some more characters then.
johnjbarton