Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
767 views
in Technique[技术] by (71.8m points)

google chrome - Is there a method I can override on a JavaScript object to control what is displayed by console.log?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...