Note: I’m going to use a specific object as an example here, but please don’t post answers specific to this example; the question is more general.
Specific example
I wrote some jQuery code like this…
$('#some_button').click(function(event) {
$.post('<some URL>', { <some parameters> },
function() { <do something on success> })
.error(function(x) {
// What is x?
});
event.preventDefault();
});
Now, for the purpose of this question, let’s assume that there is no documentation about that object x that is passed in.
An obvious thing to do might be
alert(x);
but all that will output is [object Object].
General question
What might be an easy way to find out what properties/methods an unknown object has? I’m thinking something that I’d just write during the debugging phase, no production code of course.
You may assume that jQuery is available.
Edit:
I’m fully aware of for (...), but surely that doesn’t mean there can’t be a better/easier way — I thought jQuery might have something built-in…
A general and single level basic javascript solution
Basic functionality looks like this:
Object graph issue
It will enumerate over all properties of an object. If this particular object has deep object trees you should better put this into a function and then recall it on sub object. enumerate internal sub object using the same technique. Arrays are a similar issue.
But I suppose you’ll be able to provide this kind of functionality from this starting example code.
Browser console solution
If you have development console open in your browser (in Firefox that would be Firebug) then you can easily just call this:
But there’s a problem with IE, because when it comes to a complex object is just displays
{...}which isn’t really helpful. So this approach can only be used in Chrome and Firefox+Firebug.A jQuery plugin for any browser
This is a small and simple plugin I’ve come up to enumerate an arbitrary object and display its content in browser’s console:
This code works with any browser (I actually needed it for IE, because of the previously mentioned issue with
{...}display.It parses an object graph into console provided that your browser’s console is open. In IE and Chrome that’s the built in development console and in Firefox it’s Firebug console.
You can use it as:
or
The second optional parameter is used to give your object a name when displaying it. If you don’t provide the name it will be set as
"this". Your object will be displayed as: