Search code examples
javascriptobjectinspect

How to inspect Javascript Objects


How can I inspect an Object in an alert box? Normally alerting an Object just shows an opaque representation like [object Object]. For example:

alert(document); // displays "[object HTMLDocument]"

But I want to get the properties and methods of the object in the alert box. How can I achieve this functionality, if possible? Or are there any other suggestions?

Particularly, I am seeking a solution for a production environment where console.log and Firebug are not available.


Solution

  • The for-in loops for each property in an object or array. You can use this property to get to the value as well as change it.

    Note: Private properties are not available for inspection, unless you use a "spy"; basically, you override the object and write some code which does a for-in loop inside the object's context.

    For in looks like:

    for (var property in object) loop();
    

    Some sample code:

    function xinspect(o,i){
        if(typeof i=='undefined')i='';
        if(i.length>50)return '[MAX ITERATIONS]';
        var r=[];
        for(var p in o){
            var t=typeof o[p];
            r.push(i+'"'+p+'" ('+t+') => '+(t=='object' ? 'object:'+xinspect(o[p],i+'  ') : o[p]+''));
        }
        return r.join(i+'\n');
    }
    
    // example of use:
    alert(xinspect(document));
    

    Edit: Some time ago, I wrote my own inspector, if you're interested, I'm happy to share.

    Edit 2: Well, I wrote one up anyway.