How can I look at an object in JavaScript to find out what it is?

Note: I am going to use a specific object as an example here, but please do not send answers specific to this example; the question is more general.

Specific example

I wrote 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 this question, let's assume that there is no documentation about this object xthat is being passed.

Obvious may be

alert(x);

but all that will be output [object Object].

General question

What could be an easy way to find out what properties / methods an unknown object has? Im thinking something that Id just writes in the debugging phase, without production code, of course.

You can assume jQuery is available.

Edit:

Im for (...), , , , / - , jQuery - ...

+5
6

javascript-

:

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

. , , . -, . .

, ​​ .

( Firefox Firebug), :

console.log(obj);

IE, , {...}, . , Chrome Firefox + Firebug.

jQuery

, :

$.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());
    }
});

( IE - {...}.

, . IE Chrome Firefox Firebug.

:

$.inspect(yourObject);

$.inspect(yourObject, "person");

, . , "this". :

this.name = "John"
this.lastname = "Doe"
+5

console.log .

( , ) , for(parameter in obj){ ... }

+2
console.log

.

+1

, Google Chrome Firefox, Firebug plugin, . Javascript, :

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

JSON . .

+1

javascript , , - . . " " , .

, ?

javascript , . ?

+1

console.log typeof obj .

0

All Articles