简体   繁体   中英

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.

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.

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.

You might also want to look into the debugger statement.

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 has its purpose. 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 = 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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