Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use the console to see available methods on an object?

Is there any way I can use the console to see the methods available on a JS object?

I'm thinking of something like this:

> var myArray = [1,2,3];
  undefined
> myArray
  [1, 2, 3]
> myArray.logme = function() { console.log(this); };
  function () { console.log(this); }
> myArray
  [1, 2, 3]

The second time I type myArray, I would like to see the fact that the logme() method is now available.

I want to know the answer in order to explore unfamiliar JS objects more easily.

like image 308
Richard Avatar asked Mar 06 '13 14:03

Richard


2 Answers

You can use

console.dir(myArray);

and you will get an expandable/inspectable display like this, including custom properties and the prototype object:

(from https://stackoverflow.com/a/14537759/1048572, see also What's the difference between console.dir and console.log?)

like image 154
Bergi Avatar answered Oct 08 '22 06:10

Bergi


If you're in Chrome and you could use something like the following (fairly crude) check for if a property is a function:

function showMethods(obj) {
    console.log(Object.keys(obj).filter(function(prop) {
        return typeof el[prop] == 'function';
    }));
}

Then just call it as follows:

showMethods({a: 1, b: 2, c: function () {}}) // ['c']
showMethods({a: 1, b: 2}) // []
showMethods({a: 1, b: function() {}, c: function () {}}) // ['b', 'c']
like image 42
jabclab Avatar answered Oct 08 '22 06:10

jabclab