为什么控制台不使用输入对象的`toString`方法? [英] Why the console doesn't use entered object's `toString` method?

查看:112
本文介绍了为什么控制台不使用输入对象的`toString`方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我打开控制台并输入...

If I open the console and enter...

var f=function(a){
    this.toString=function(){
        return "-->"+a;
    }
},i=new f(5);
i;

...它返回({toString:(function(){return - >+ a;})})

但如果我输入...

var f=function(a){
    this.toString=function(){
        return "-->"+a;
    }
},i=new f(5);
alert(i);

...它提醒 - > 5

我非常重要,但我希望第一个代码返回 - > 5 。有没有办法做到这一点,或者是否故意控制台不使用 toString

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?

推荐答案

它用于调试使用,所以告诉你所有关于对象的说法都很有用。

It's intended for debugging use, so telling you all there is to say on an object is likely to be useful.

毕竟,如果你想要调用 toString()的结果,你会问它,用 i.toString()+ i ,但如果这是默认行为,则无法获得更深层次的表示。

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.

这篇关于为什么控制台不使用输入对象的`toString`方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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