5

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...

Timwi
  • 65,159
  • 33
  • 165
  • 230

6 Answers6

5

A general and single level basic javascript solution

Basic functionality looks like this:

var s = "";
for(var p in obj)
{
    s += p + " = " + obj[p] + "\n";
}
alert(s);

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:

console.log(obj);

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:

$.extend({
    inspect: function(obj,n){
        n = n || "this";
        if ($.isArray(obj)) {
            for (var x = 0; x < obj.length; x++) {
                $.inspect(obj[x], n + "[" + x + "]");
            }
            return;
        }
        if ($.isPlainObject(‌​obj)) {
            for (var p in obj){
                $.inspect(obj[p], n + "." + p);
            }
            return;
        }
        console.log(n + " = " + obj.toString());
    }
});

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:

$.inspect(yourObject);

or

$.inspect(yourObject, "person");

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:

this.name = "John"
this.lastname = "Doe"
Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
  • Your procedure will loop endlessly for any self-referencing (i.e. circular) objects. – davin Jun 13 '11 at 12:14
  • @davin: That's true. I could as well put the third parameter to define `maxDepth` – Robert Koritnik Jun 13 '11 at 12:17
  • That is one solution, although it's pretty ugly because usually people use a loose upper bound. So for maxDepth iterations you will continue to print out all the same values. And the only way to have a tight bound is to know the object, which in general is tough, and in particular the OP said he isn't familiar with the object. And if you know the object, then you often don't need to inspect it. There are other solutions that are slightly less efficient, although since this is a development routine would be suitable, like storing references. – davin Jun 13 '11 at 12:21
  • What if x is a host object, or string, or boolean or anything other than an Array or "plain" Object? – RobG Jun 13 '11 at 12:39
  • 1
    @RobG, then it prints it after calling it's `toString` method. Only host objects may prove tricky, but that's much more of a corner case IMO. – davin Jun 13 '11 at 12:54
  • @RobG: Last line in routine prints it out: `console.log(n + " = " + obj.toString());` because arrays and objects recursively call this function and then return from it. – Robert Koritnik Jun 13 '11 at 13:46
  • It treats Number objects and primitives the same, also for strings. If given an empty array or object (or array of emtpy objects) it prints nothing. Given null or undefined it throws an error, and so on. – RobG Jun 14 '11 at 02:28
2

console.log was built for that.

Alternatively (although I'm not sure what could be better than the first option) your own recursive implementation that loops through the objects properties with a simple for(parameter in obj){ ... }

davin
  • 44,863
  • 9
  • 78
  • 78
1
console.log

will usually give you a better idea of the properties an object has.

Mick Hansen
  • 2,685
  • 18
  • 14
1

Your best bet would be to use a browser like Google Chrome or Firefox with the Firebug plugin then you can add a breakpoint and inspect the object. If it is just a simple Javascript object you could just loop through the properties like so:

for(name in object) { 
  alert("name: " + name + "value:" + object[name]);
}

Another option might be to serialize to JSON and output that. A solution for doing that can be found here.

Community
  • 1
  • 1
John Duff
  • 38,090
  • 5
  • 35
  • 45
1

It is difficult in javascript to write a general function to determine whether an identifier references any particular type of value. Most such functions are limited to specific cases. A general "what is this" function is practically impossible if not limited to specific bounds.

If such a function was available, what would you do with it?

The general approach in javascript is to test for the properties or capabilities that are required for a particular purpose. What is the point in going further?

RobG
  • 142,382
  • 31
  • 172
  • 209
0

console.log and typeof obj will suffice.

marko
  • 10,684
  • 17
  • 71
  • 92