I know this is possible in python, but can i get a list of methods for a javascript object?
+4
A:
You can loop over the properties in the object and test their type.
for(var prop in whatever) {
if(typeof whatever[prop] == 'function') {
//do something
}
}
Jani Hartikainen
2010-07-15 04:15:07
+1 any way 2 get the arguments to a function?
deostroll
2010-07-15 04:38:36
No. All native JavaScript functions accept any number of arguments anyway.
Tim Down
2010-07-15 08:34:22
+2
A:
To add to the existing answers, ECMAScript 5th ed. provides a way to access all properties of an object (even the non-enumerable ones) using the method Object.getOwnPropertyNames
. When trying to enumerate the properties of native objects such as Math
, a for..in
for(var property in Math) {
console.log(property);
}
will print nothing on the console. However,
Object.getOwnPropertyNames(Math)
will return:
["LN10", "PI", "E", "LOG10E", "SQRT2", "LOG2E", "SQRT1_2", "abc", "LN2", "cos", "pow", "log", "tan", "sqrt", "ceil", "asin", "abs", "max", "exp", "atan2", "random", "round", "floor", "acos", "atan", "min", "sin"]
You could write a helper function on top of this that only returns methods given an object.
function getMethods(object) {
var properties = Object.getOwnPropertyNames(object);
var methods = properties.filter(function(property) {
return typeof object[property] == 'function';
});
return methods;
}
> getMethods(Math)
["cos", "pow", "log", "tan", "sqrt", "ceil", "asin", "abs", "max", "exp", "atan2", "random", "round", "floor", "acos", "atan", "min", "sin"]
Support for ECMAScript 5th ed. is somewhat bleak at this point, as only Chrome, IE9pre3, and Safari/Firefox nightlies support it.
Anurag
2010-07-15 04:24:05
@Anurag, yes, I'm really happy to see IE9 going in a good path, I've found only a few bugs (8+) regarding property descriptors and `Object.create`, hope this weekend I get some time to report them. :)
CMS
2010-07-15 05:21:48