简体   繁体   English

获得比“ [object Object]”更有用的值进行调试吗?

[英]Get a more useful value than “[object Object]” for debugging?

Couldn't there a be a environment flag in JavaScript so you could turn on some metadata for objects. JavaScript中没有环境标志,因此您可以为对象打开一些元数据。

So instead when you are debugging and get: 因此,当您调试并获得以下信息时:

[object Object]

you would get the variable name and type: 您将获得变量名称和类型:

[foo String]

why isn't this possible? 为什么这不可能呢?

JSON.stringify might be what you are looking for, though it won't give you the name of the variable – JavaScript simply can't do that without 3rd party tools. JSON.stringify可能就是您想要的,尽管它不会为您提供变量的名称-如果没有第三方工具,JavaScript根本无法做到这一点。

The constructor function of your object can be reached by using its constructor property, though there's no guarantee with this as the constructor property is writable. 您可以使用对象的构造函数属性来访问其constructor ,尽管不能保证,因为构造函数属性是可写的。

You might also want to look into the debugger statement. 您可能还需要研究debugger语句。

A bit hacky , but it can help you to find what is your object source : 有点古怪,但是它可以帮助您找到什么是对象源:

function Foo()
{}

var toClass = function(a)
{
    var _name = a.constructor.toString().match(/^function (\w+)/i); //\w probably should be enhanced
    console.log(_name[1])
}

toClass( new Foo()) //Foo
toClass( [1, 2]) //Array
toClass( new Date()) //Date
toClass( {"a":2}) //Object

Aside note : don't override toString just for debugging. 撇开注意: 不要仅为了调试覆盖toString toString has its purpose. toString有其用途。 and should be used as it was meant to be used. 并应按原意使用。

To directly answer your question about just flipping a "global flag" instead of changing your debugging methodology: 要直接回答有关仅翻转“全局标志”而不是更改调试方法的问题,请执行以下操作:

Assuming you'd only do this during debugging, you can temporarily override the Object.prototype.toString to return a JSON representation of objects: 假设只在调试期间执行此操作,则可以临时重写Object.prototype.toString以返回对象的JSON表示形式:

Object.prototype.toString = function () { return JSON.stringify(this); };

Then in the browser console: 然后在浏览器控制台中:

var obj = { a: 42 };
console.log('My object: ' + obj);

Will give you: 会给你:

My object: {"a":42}

Even if this answers your question, I don't recommend a global override of a base method because it has the potential to cause catastrophic issues. 即使这回答了您的问题,我也不建议对基本方法进行全局替代,因为它有可能导致灾难性的问题。 Try relying on unit tests and breakpoints + debugging as others have suggested in comments. 尝试依靠其他人在评论中建议的单元测试和断点+调试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM