Crawlicious

tools for web business

Introspecting Javascript Objects

| 0 comments

One of the most annoying things with javascript is trying to see what is inside of an object.  In python you simply print (‘attributes=%s’%dir(obj)), and in php you simply use var_dump(obj), or if you want to format it into a string, you can use echo “attributes=” . var_export(obj) ;  But with Javascript I really haven’t had an easy way to introspect the attributes of an object.  Until now.

I have been using a great tool for debugging javascript called FireBug, it is a plugin for firefox.  So, firebug has a way to do object introspection via the DOM tab.  When you get an object that you want to analyze simply do something like this in your code (at a global level) var MYOBJECTREFERENCE = new Object();  Now, wherever you have access to that object you want to introspect (in an event handler or whatever), you simply say MYOBJECTREFERENCE.XYZ = obj;  Then, refresh, trigger whatever event it took to generate obj, and then look in firebug’s DOM explorer window for MYOBJECTREFERENCE.XYZ.

YAY!  Now there is an easy way to introspect objects in javascript.  If you know of other ways to do this, please post them for us all to see.

Eric

UPDATE: 12/8/2009

I found another way to do this.  The code is from RefactorMyCode.com .  Mine is a little different because I was getting errors and I had to protect against them a bit… Here you go!


function odump(obj, depth, max) {
 depth = depth || 0;
 max = max || 2;

 if (depth > max)
 return false;

 var indent = "";
 for (var i = 0; i < depth; i++)
 indent += "  ";

 var output = "";
 for (var key in obj){
 // skiplist
 if (key == "domConfig" || key == "selectionStart" || key == "selectionEnd" || key == "schemaTypeInfo") {
 output += "\n" + indent + key + "**: ";
 } else {
 try {
 output += "\n" + indent + key + ": ";
 switch (typeof obj[key]){
 case "object": output += odump(obj[key], depth + 1, max); break;
 case "function": output += "function"; break;
 default: output += obj[key]; break;
 }
 } catch(err) {
 alert("add key=" + key + " to your skiplist because of: err=" + err);
 }
 }
 }
 return output;
}

Leave a Reply