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.
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.
Share Improve this question edited Mar 6, 2013 at 14:33 Paolo 21.1k21 gold badges76 silver badges121 bronze badges asked Mar 6, 2013 at 14:17 RichardRichard 65.6k135 gold badges356 silver badges571 bronze badges 3-
If you're referring to Chrome's console, then you could simply type
myArray.
(with the dot) this will reveallogme
along with all other Array methods – juco Commented Mar 6, 2013 at 14:20 - Have a look a this q/a. stackoverflow./questions/5523747/… – Paolo Commented Mar 6, 2013 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 Commented Mar 6, 2013 at 14:27
2 Answers
Reset to default 8You 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./a/14537759/1048572, see also What's the difference between console.dir and console.log?)
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']