是否可以覆盖JavaScript的toString()函数,为调试提供有意义的输出? [英] Is it possible to override JavaScript's toString() function to provide meaningful output for debugging?

查看:104
本文介绍了是否可以覆盖JavaScript的toString()函数,为调试提供有意义的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在JavaScript程序中的一个对象 console.log()时,我只看到输出 [object Object] ,这对于找出什么对象(甚至是什么类型的对象)并不是很有帮助。

When I console.log() an object in my JavaScript program, I just see the output [object Object], which is not very helpful in figuring out what object (or even what type of object) it is.

在C#中,我习惯于覆盖 ToString()可以自定义对象的调试器表示。在JavaScript中有什么类似的东西吗?

In C# I'm used to overriding ToString() to be able to customize the debugger representation of an object. Is there anything similar I can do in JavaScript?

推荐答案

您可以覆盖 toString 在Javascript中。参见示例:

You can override toString in Javascript as well. See example:

function Foo() 
{
}

// toString override added to prototype of Foo class
Foo.prototype.toString = function()
{
    return "[object Foo]";
}

var f = new Foo();
alert(f);  // popup displays [object Foo]

请参阅这个关于如何在JavaScript中确定对象类型名称的讨论。

See this discussion on how to determine object type name in JavaScript.

这篇关于是否可以覆盖JavaScript的toString()函数,为调试提供有意义的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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