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

查看:18
本文介绍了是否可以覆盖 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?

推荐答案

您也可以在 Javascript 中覆盖 toString.见示例:

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();
console.log("" + f); // console displays [object Foo]

参见这个 讨论如何在 JavaScript 中确定对象类型名称.

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

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

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