views:

62

answers:

2

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
+1 any way 2 get the arguments to a function?
deostroll
No. All native JavaScript functions accept any number of arguments anyway.
Tim Down
+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
reason for down vote?
Anurag
+1, I don't see any reason for a downvote. BTW, IE9pre3 also supports it.
CMS
thanks @CMS, it's good to see IE on its toes with v9. Updated answer.
Anurag
@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