7

I know this is possible in python, but can i get a list of methods for a javascript object?

4 Answers 4

12

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
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

No. All native JavaScript functions accept any number of arguments anyway.
@deostroll In a browser that implements toSource, firefox only right now, you can use func.toSource().match(/\(([^\(\)]+)\)/)[1]. This won't work on built in functions though.
6

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.

3 Comments

+1, I don't see any reason for a downvote. BTW, IE9pre3 also supports it.
thanks @CMS, it's good to see IE on its toes with v9. Updated answer.
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. :)
1

This function receives an arbitrary object and returns the name of it's prototype, a list with all it's methods and an object with the name of it's properties (and their types). I haven't the opportunity of testing it in a browser, but it works with Nodejs (v0.10.24).

function inspectClass(obj) {    
    var objClass, className;   
    var classProto;
    var methods = [];
    var attributes = {};
    var t, a;
    try {
        if (typeof(obj) != 'function') {
            objClass = obj.constructor;
        } else {
            objClass = obj;      
        }
        className = objClass.name;
        classProto = objClass.prototype        
        Object.getOwnPropertyNames(classProto).forEach(function(m) {
            t = typeof(classProto[m]);
            if (t == 'function') {
                methods.push(m);
            } else {
                attributes[m] = t;
            }       
        });
    } catch (err) {
        className = 'undefined';
    }
    return { 'ClassName' : className,
             'Methods' : methods,
             'Attributes' : attributes
    }
}

Example (with Nodejs):

console.log(inspectClass(new RegExp("hello")));

Output:

{ ClassName: 'RegExp',
  Methods: [ 'constructor', 'exec', 'test', 'toString', 'compile' ],
  Attributes: 
   { source: 'string',
     global: 'boolean',
     ignoreCase: 'boolean',
     multiline: 'boolean',
     lastIndex: 'number' } }

The following examples also work with Nodejs:

console.log(inspectClass(RegExp));
console.log(inspectClass("hello"));
console.log(inspectClass(5));
console.log(inspectClass(undefined));
console.log(inspectClass(NaN));
console.log(inspectClass(inspectClass));

Comments

0

A single-line solution

Object.getOwnPropertyNames(JSON).filter(function(name){ return 'function' === typeof JSON[name]; })

[ 'parse', 'stringify' ]

Object.getOwnPropertyNames(String).filter(function(name){ return 'function' === typeof String[name]; })

[ 'fromCharCode', 'fromCodePoint', 'raw' ]

Object.getOwnPropertyNames(Array).filter(function(name){ return 'function' === typeof Array[name]; })

[ 'isArray', 'from', 'of' ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.