Skip to content

Instantly share code, notes, and snippets.

@reagent
Created January 21, 2011 04:13
Inspect JavaScript objects -- useful for debugging.
var Inspector = function(target) {
var inspector = this,
target = target;
function padding(indentationLevel) {
paddingText = '';
for (var i = 0; i < indentationLevel; i++) {
paddingText += ' ';
}
return paddingText;
}
function dumpObject(object, indentationLevel) {
indentationLevel = indentationLevel || 0;
output = '';
for (attribute in object) {
if (object.hasOwnProperty(attribute)) {
thing = object[attribute];
prefix = padding(indentationLevel) + attribute + ": ";
if (typeof(thing) == 'object') {
output += prefix + "{\n" +
dumpObject(thing, indentationLevel + 1) +
padding(indentationLevel) +
"}\n";
} else {
output += prefix + object[attribute] + "\n";
}
}
}
return output;
}
inspector.inspect = function() {
return dumpObject(target);
}
}
Object.prototype.inspect = function() {
inspector = new Inspector(this);
return inspector.inspect();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment