6

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.

Paolo
  • 20,112
  • 21
  • 72
  • 113
Richard
  • 62,943
  • 126
  • 334
  • 542
  • If you're referring to Chrome's console, then you could simply type `myArray.` (with the dot) this will reveal `logme` along with all other Array methods – juco Mar 06 '13 at 14:20
  • Have a look a this q/a. http://stackoverflow.com/questions/5523747/equivalent-of-pythons-dir-in-javascript – Paolo Mar 06 '13 at 14:26
  • @juco - that's cool, thank you. I don't suppose you know any way to see just the non-Array-prototype methods, though? – Richard Mar 06 '13 at 14:27

2 Answers2

8

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?)

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

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']
jabclab
  • 14,786
  • 5
  • 54
  • 51