Andersson
Andersson

Reputation: 52665

How to get list of all applicable methods

I just start learning JavaScript and I faced with problem: I don't know how to check what exactly I can do with my variables (for example, how I can manage string or array). In Python there are very useful methods dir() and help() that allow user to get list of all applicable methods and find out how to use them:

>>>my_number = 1
>>>dir(my_number)

This will return

['bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

the list of methods I can apply to my_number variable

Then I can get description of each method:

>>>help(my_number.real)

Help on int object:

class int(object)
|  int(x=0) -> integer
|  int(x, base=10) -> integer
|
|  Convert a number or string to an integer, or return 0 if no arguments
|  are given.  If x is a number, return x.__int__().  For floating point
|  numbers, this truncates towards zero...

So is there any similar function in JavaScript so I can call it like console.log(getAllMethodsFor(myNumber)) ? This could significantly simplify process of language learning...

Upvotes: 1

Views: 7898

Answers (3)

deceze
deceze

Reputation: 522145

There is no such thing by default, but you could write one simply by iterating the properties of the given object:

for (var prop in obj) {
    if (typeof obj[prop] == 'function') {
        console.log(prop);
    }
}

Having said that, that's still missing the integrated docstrings for help(). Typically in Javascript development you're reading the (hopefully) accompanying documentation and/or use an interactive console like Chrome's Web Inspector to inspect objects in a more GUI-like manner.

Upvotes: 2

georg
georg

Reputation: 214959

Nothing built-in, but easy to write:

function dir(obj) {

    if(obj === null)
        return [];

    var uniq = a => a.filter((x, i) => a.indexOf(x) === i);

    return uniq(dir(Object.getPrototypeOf(obj)).concat(
        Object.getOwnPropertyNames(obj).filter(p => typeof obj[p] === 'function')
    ));

}

document.write(dir(1))
document.write("<hr>");
document.write(dir("abc"))

Regarding help, there's no such thing either, but typing mdn <method name> in google usually does the trick.

Upvotes: 2

gurvinder372
gurvinder372

Reputation: 68393

you can get the properties of a variable and check if the typeof property is a function

function getAllFunctions(myvar)
{
   var allMethods = [];
   for( var property in myvar)
   {
      if (typeof myvar[property] == "function")
      {
         allMethods.push(property);
      }
   }
   return allMethods ;
}

Upvotes: 2

Related Questions