有没有一种方法可以覆盖JavaScript对象来控制console.log显示的内容? [英] Is there a method I can override on a JavaScript object to control what is displayed by console.log?

查看:122
本文介绍了有没有一种方法可以覆盖JavaScript对象来控制console.log显示的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我特别想到Chrome,不过Firebug会很有趣。我试过toString()和valueOf(),但都没有被使用。有趣的是,如果我接受一个函数,它会显示函数定义 - 但是如果我添加一个toString()方法,它将显示空值!

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?

推荐答案

我无法知道。你最好的选择是在你想记录的对象上定义一个 toString()方法,然后直接或间接调用它:

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

这篇关于有没有一种方法可以覆盖JavaScript对象来控制console.log显示的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆