Skip to content

Instantly share code, notes, and snippets.

@phillipalexander
Created July 19, 2013 00:52
Show Gist options
  • Save phillipalexander/6034293 to your computer and use it in GitHub Desktop.
Save phillipalexander/6034293 to your computer and use it in GitHub Desktop.
X-Ray Spectacles For Your JavaScript Objects
var xRay = function (obj, key, spaces) {
var i,
k,
keyTypeStr,
xrayResult,
indent;
key = key || "";
spaces = spaces || 1;
indent = "";
i = 1;
while (i < spaces) {
indent += " ";
i++;
}
keyTypeStr = " (" + typeof key + ")";
if (spaces === 1) {
keyTypeStr = "(self)";
}
xrayResult = indent + key + keyTypeStr + " : ";
if (typeof obj === "object" && obj !== null) {
xrayResult += typeof obj + "\n";
for (k in obj) {
if (obj.hasOwnProperty(k)) {
xrayResult += xRay(obj[k], k, spaces + 1);
}
}
} else {
xrayResult += "" + obj + " (" + typeof obj + ") \n";
}
return xrayResult;
};
a = [1, function(a){alert("hey")}, 'c'];
a.hidden="secret message";
// console.log(a);
console.log(xRay(a));
var Inspect = {
TYPE_FUNCTION: 'function',
// Returns an array of (the names of) all methods
methods: function (obj) {
var testObj = obj || self;
var methods = [];
for (var prop in testObj) {
if (typeof testObj[prop] == Inspect.TYPE_FUNCTION && typeof Inspect[prop] != Inspect.TYPE_FUNCTION) {
methods.push(prop);
}
}
return methods;
},
// Returns an array of (the names of) all properties
properties: function (obj) {
var testObj = obj || self;
var properties = [];
for (var prop in testObj) {
if (typeof testObj[prop] != Inspect.TYPE_FUNCTION && typeof Inspect[prop] != Inspect.TYPE_FUNCTION) {
properties.push(prop);
}
}
return properties;
}
};
/*tests*/
var a = ['a', 'b', 'c', 'd', 'e'];
a.prop = true;
console.log(Inspect.properties(a));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment