Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Created October 5, 2011 15:46
Show Gist options
  • Save WebReflection/1264775 to your computer and use it in GitHub Desktop.
Save WebReflection/1264775 to your computer and use it in GitHub Desktop.
could be used by an IDE to inspect objects runtime
// could be used to inspect objects runtime
// e.g. with IDE for suggestion
// requires a modern JS engine in the IDE
var properties = function (
getNames, // alias Object.getOwnPropertyNames
getDescriptor,// alias Object.getOwnPropertyDescriptor
has, // alias {}.hasOwnProperty
toString // alias Function.prototype.toString
) {
// (C) WebReflection - Mit Style License
function inspect(key) {
var
self = this,
object = self.origin,
methods = self.methods,
properties = self.properties,
descriptor = getDescriptor(object, key)
;
if (
descriptor && // valid descriptor
!/^-?\d+$/.test(key) && // not a numeric index
!~methods.indexOf(key) && // not already in the methods list
!~properties.indexOf(key) // not already in the properties list
) {
// if there is a value and it's a function
if (
has.call(descriptor, "value") &&
typeof descriptor.value == "function"
) {
// extract the signature and concatenate it to the key
// e.g. doStuff(stuff,moreStuff)
self.methods.push(key + toString.call(descriptor.value).replace(
/^[^(]+?(\([^)]*?\))[^\x00]+$/,
"$1"
));
}
// otherwise it's considered a property (even getters/setters)
else {
self.properties.push(key);
}
}
}
// the exposed function
return function properties(object) {
var result = {
properties: [],
methods: [],
origin: object
};
do {
// add all possible properties and methods
getNames(object).forEach(inspect, result);
} // up to the initial inheritance
while (object = object.__proto__);
// avoid leaks
delete result.origin;
// return the result with all properties and methods
return result;
};
}(
Object.getOwnPropertyNames,
Object.getOwnPropertyDescriptor,
{}.hasOwnProperty,
Function.toString
);
/* example
console.log(properties({
getName: function () {
return this._name;
},
setName: function (name) {
this._name = name;
}
}));
//*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment